Run your own code when a visitor accepts or declines the cookie banner
TermsFeed Privacy Consent (CMP) offers 2 ways to run your code at consent: a vendor tag follows the consent state on every page view, and a callback reports each saved answer. Neither one is an event that fires once at the click. An on-accept vendor tag runs again on every page a returning visitor opens, and an answer callback never runs on page load, apart from a Global Privacy Control override.
Pick the method by when your code has to run, then follow the steps for it. The setup takes 3 steps and about 20 minutes. You need edit access to your site <head> and to the vendors of your consent banner in the TermsFeed app.
Choose between a vendor tag and a callback
Use a vendor tag for code that runs on every page view while the visitor allows it, and a callback for code that reacts to the answer itself. A vendor tag suits a tracker or a call that lets a widget start. A callback suits code that sends the new answer to your server or stops a feature the visitor turns off. Many sites use both, a vendor tag for the feature and a callback for the change.
The table compares when each one runs.
| Situation | On-accept vendor tag | Answer callback |
|---|---|---|
| The visitor clicks I Agree | Runs at once, with no reload | acceptedAll or acceptedSome runs |
| A visitor who accepted earlier opens another page | Runs on every page view | Does not run |
| A first visit under the opt-out model, with no click | Runs | Does not run |
| The visitor withdraws consent in the Preferences Center | Keeps what it started until the next page load | acceptedSome or rejectedAll runs |
| The visitor saves the same answer again | Does not run again on that page view | Runs on every save |
| The visitor accepts a single vendor | Runs for that vendor | Reports whole vendor categories only |
| Global Privacy Control overrides a stored acceptance on load | Does not run | rejectedAll runs, with no click |
Read a trigger action as a state of the page view, not as an event. On accept means the vendor is allowed in the current page view. On decline means a saved answer declines the vendor and the vendor has not been allowed in the current page view. Look up each rule in Vendor Tag Trigger Actions.
A vendor with no vendor tags and no replaceable tags runs nothing. Privacy Consent lists it in the Preferences Center and records the answer, while code you leave in your page outside a vendor runs for every visitor.
Step 1: Put page-view code in an on-accept vendor tag
Open the vendor in the TermsFeed app, select the "JavaScript tags" tab, and turn on "If allowed". Paste your code inside a <script> element, then click "Save vendor".
<script>
window.myApp.startAnalytics();
</script>
Privacy Consent reads every vendor tag slot as HTML, so code without a <script> element is text to the page. The code lands at the end of <body>, shows to visitors as text, and never runs. A pasted window.myApp.startAnalytics(); with no <script> element appears as that line at the bottom of every page that allows the vendor. The vendor form refuses to save such code and shows "Code outside a <script> tag shows on your website as text and never runs." under the field.
Privacy Consent inserts each vendor tag at most once per page view. The code runs on the click that allows the vendor and again on every later page load while the vendor stays allowed. Write it for every page view, not for the first acceptance only. Choose the slot for code of other types with Vendor Tag Matrix.
Call a function your page defines
Define the function in an ordinary <script> in your <head>, above the Privacy Consent snippet. Privacy Consent inserts vendor tags only after its own script and settings have loaded, so a function defined earlier in the <head> exists by then. A function defined in a bundle that loads later, with defer or after the page, is not always ready.
<script>
window.myApp = window.myApp || {};
window.myApp.startAnalytics = function () {
console.log('Analytics allowed on this page view');
};
</script>
Optional chaining such as window.myApp?.startAnalytics?.() hides a function that does not exist yet. The call does nothing and prints nothing, so the vendor tag looks broken with no error. Call the function without ?. while you test, and a missing function prints a TypeError in the Console tab, since Privacy Consent does not catch errors in vendor tag code.
Step 2: Report accepts and withdrawals from the callbacks
Compare each answer with the one in force at page load, because Privacy Consent has no withdrawal callback. An answer callback reports the vendor categories the visitor accepted, not what changed, and it runs on every save, including one that changes nothing. The block keeps the previous answer and calls your handlers only for a vendor category that changed.
Put the block in your <head>, below the tfConsent() reader and above the Privacy Consent snippet. Copy the reader from Step 1: Add the Privacy Consent reader function.
<script>
var tfCategoryIds = ['functionality', 'analytics', 'advertising', 'marketing'];
var tfConsentAtLoad = tfConsent();
var tfGrantedBefore = [];
function tfGrantedAtLoad() {
var consent = tfConsentAtLoad;
if (!consent.chosen && window.termsfeed_privacy_consent.v1.visitor.isOptOutModel) {
return tfCategoryIds.slice();
}
return tfCategoryIds.filter(function (id) { return consent[id] === 'granted'; });
}
function tfCompare(categories) {
tfCategoryIds.forEach(function (id) {
var was = tfGrantedBefore.indexOf(id) !== -1;
var now = categories.indexOf(id) !== -1;
if (!was && now) onConsentGranted(id);
if (was && !now) onConsentWithdrawn(id);
});
tfGrantedBefore = tfCategoryIds.filter(function (id) { return categories.indexOf(id) !== -1; });
}
function onConsentGranted(category) {
console.log('Granted at this answer:', category);
}
function onConsentWithdrawn(category) {
console.log('Withdrawn at this answer:', category);
}
var callbacks = {
initialized: function () { tfGrantedBefore = tfGrantedAtLoad(); },
acceptedAll: function (categories) { tfCompare(categories); },
acceptedSome: function (categories) { tfCompare(categories); },
rejectedAll: function () { tfCompare([]); }
};
if (window.termsfeed_privacy_consent !== undefined)
window.termsfeed_privacy_consent.v1.callbacks(callbacks);
else
window.termsfeed_privacy_consent_callbacks = callbacks;
</script>
The block reads the stored answer before the Privacy Consent script runs, and initialized turns it into the vendor categories granted at load. Reading it that early keeps an acceptance that a Global Privacy Control override replaces on load, so the rejectedAll of the override reports it as withdrawn. A first visit under the opt-out model counts every vendor category as granted, because every vendor runs there with no answer saved. The block reads isOptOutModel from window.termsfeed_privacy_consent.v1.visitor inside initialized, the moment its flags are set.
Replace the 2 handlers with your own code. Stop your feature in onConsentWithdrawn() where it offers a stop method, because Privacy Consent does not undo a script that ran. A vendor the visitor withdraws keeps running until the next page load, and the cookies it set stay until they expire.
Merge the block into any callbacks already on your page, since each v1.callbacks() call replaces all 4. A vendor category the visitor accepts only in part is missing from categories, so the block reports it as withdrawn. Compare single vendors with the function in Read each vendor for a vendor-accurate answer.
Why on decline is not a withdrawal hook
An on-decline vendor tag does not run on the page view where a visitor withdraws consent from a vendor that already ran. Privacy Consent saves and logs the withdrawal at once, and the vendor keeps everything it started on that page. The on-decline code runs from the next page load, on every page view while the answer stands.
On decline skips 2 more cases. It does not run before a first answer, so a visitor who ignores the consent banner does not get on-decline code. It does not run for a vendor added after the visitor answered, until the visitor answers again, because that visitor was never asked about it.
Use on decline for content that stands in for a refused service, such as a contact link in place of a chat widget. Name a function the tag calls after the state it shows, such as showChatFallback(), and keep code for the withdrawal itself in the callbacks of Step 2. Plan what each vendor does after a withdrawal with Let Visitors Withdraw Consent.
Step 3: Verify both paths in the Console tab
Run this check on a visit that shows the consent banner. Put the vendor tag of Step 1 in an Analytics vendor. Put the window.myApp function, the tfConsent() reader, and the block of Step 2 in your <head>. A new private window has no cached settings, so it gets the vendor you saved.
- Close every private window, open a new one, open Chrome DevTools, and select the Console tab.
- Load your site. No
Analytics allowed on this page viewline and noGranted at this answer:line appear while the consent banner waits. - Click I Agree. The Console tab prints
Analytics allowed on this page viewonce, andGranted at this answer:once for each of the 4 vendor categories other than Essential. - Reload the page.
Analytics allowed on this page viewprints again, with noGranted at this answer:line beside it. - Open the Preferences Center, turn off the Analytics vendor category, and click Save Preferences. The Console tab prints
Withdrawn at this answer: analytics, andAnalytics allowed on this page viewdoes not print again. - Reload the page.
Analytics allowed on this page viewno longer prints. A search of the Elements tab fortermsfeed-pc1-vendor-tag-id=does not find the Analytics vendor ID followed by-javascript.