This article describes how to use the addEventListener and removeEventListener commands in the __tcfapi() function. The addEventListener command is leveraged to listen for changes in the user's consent status during a pageview. The removeEventListener command removes the listener created.
The addEventListener command registers a callback function with a CMP. The listener's callback is triggered whenever the consent string status has changed. To set up an event listener you pass three arguments to the __tcfapi() function:
the 'addEventListener' command
the version of the framework
a callback function
The following are the possible events returned.
eventStatus | Description |
| This is the event status when a TC String is available to any calling scripts on the page. . |
| This is the event status whenever the UI is surfaced or re-surfaced to a user. |
| This is the event status whenever a user has confirmed or re-confirmed their choices. |
The listener is registered with an ID for later removal.
The removeEventListener command removes the event listener. To remove an event listener, you pass four arguments to the __tcfapi() function:
The 'removeEventListener' command
The version number of the framework
A callback function
The ID of the listener to be removed
If successful the listener is removed and the value of true is passed to the callback function. If it was not successful then it means it could not find a listener with the ID value passed.
Below is an example of the addEventListener and removeEventListener commands being used together.
__tcfapi('addEventListener', 2, function(tcData,success){​if(success && tcData.eventStatus === 'tcloaded') {​// do something with tcData.tcStringconsole.log(tcData.tcString);// remove the ourself to not get called more than once__tcfapi('removeEventListener', 2, function (success) {​if(success) {​// oh good...console.log('removed: '+tcData.listenerId);}​}, tcData.listenerId);​​} else {​// do something else​}​});
If you have any additional question about these functions, please consult the IAB's documentation.