You can extend the window.__tcfapi functionality by passing a map of custom commands to the CmpApi constructor.
Requirements:
- Custom functions must accept a
callback as the first parameter. - The CMP is responsible for validating and handling errors within these functions.
Middleware Pattern:
Starting from version 1.1.0, if a custom command name overlaps with a built-in command ("ping", "getTCData", "getInAppTCData", "getVendorList"), the custom command acts as middleware. It receives the built-in command's response and must call a next() function to pass the response along to the original caller.
import {CmpApi} from '@iabtechlabtcf/cmpapi';
const cmpApi = new CmpApi(1, 3, false, {
// Standard custom command
'bingo': (callback, dogName) => {
callback(`There was a farmer who had a dog, and ${dogName} was his name-o`);
},
// Middleware for a built-in command
'getTCData': (next, tcData, status) => {
// Note: when used with 'removeEventListener', tcData might be a boolean
if (typeof tcData !== 'boolean') {
tcData.reallyImportantExtraProperty = true;
}
// You MUST call next() or the caller's callback will never execute
next(tcData, status);
},
});
// Calling a custom command via the global __tcfapi
__tcfapi('bingo', 2, (lyrics, success) => {
if(success) console.log(lyrics);
}, 'Bingo');