Skip to content

Commit

Permalink
Add User ID Targeting to googletag.cmd as a fallback when GPT API is …
Browse files Browse the repository at this point in the history
…not ready (#5925)

* Add User IDs to googletag.cmd

The purpose of this change is to allow the userIdTargeting module to function even when googletag has not been defined yet.

* Fixing indentation errors

Fixing indentation errors thrown by

* Fix 'googletag' is not defined errors

* Added unit test for userIdTargeting fallback
  • Loading branch information
lyubomirshishkov authored Nov 9, 2020
1 parent f9fdc9c commit 7efc333
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
14 changes: 8 additions & 6 deletions modules/userIdTargeting.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,16 @@ export function userIdTargeting(userIds, config) {

if (!SHARE_WITH_GAM) {
logInfo(MODULE_NAME + ': Not enabled for ' + GAM);
}

if (window.googletag && isFn(window.googletag.pubads) && hasOwn(window.googletag.pubads(), 'setTargeting') && isFn(window.googletag.pubads().setTargeting)) {
} else if (window.googletag && isFn(window.googletag.pubads) && hasOwn(window.googletag.pubads(), 'setTargeting') && isFn(window.googletag.pubads().setTargeting)) {
GAM_API = window.googletag.pubads().setTargeting;
} else {
SHARE_WITH_GAM = false;
logInfo(MODULE_NAME + ': Could not find googletag.pubads().setTargeting API. Not adding User Ids in targeting.')
return;
window.googletag = window.googletag || {};
window.googletag.cmd = window.googletag.cmd || [];
GAM_API = function (key, value) {
window.googletag.cmd.push(function () {
window.googletag.pubads().setTargeting(key, value);
});
};
}

Object.keys(userIds).forEach(function(key) {
Expand Down
10 changes: 10 additions & 0 deletions test/spec/modules/shareUserIds_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@ describe('#userIdTargeting', function() {
pubads.setTargeting('test', ['TEST']);
config.GAM_KEYS.tdid = '';
userIdTargeting(userIds, config);
expect(pubads.getTargeting('tdid')).to.be.an('array').that.is.empty;
expect(pubads.getTargeting('test')).to.deep.equal(['TEST']);
});

it('User Id Targeting is added to googletag queue when GPT is not ready', function() {
let pubads = window.googletag.pubads;
delete window.googletag.pubads;
userIdTargeting(userIds, config);
window.googletag.pubads = pubads;
window.googletag.cmd.map(command => command());
expect(window.googletag.pubads().getTargeting('TD_ID')).to.deep.equal(['my-tdid']);
});
});

0 comments on commit 7efc333

Please sign in to comment.