Skip to content

Instantly share code, notes, and snippets.

@frankiehayward
Created December 5, 2019 23:25
Show Gist options
  • Save frankiehayward/846a6ebd774a5c6b0618e02ab606909d to your computer and use it in GitHub Desktop.
Save frankiehayward/846a6ebd774a5c6b0618e02ab606909d to your computer and use it in GitHub Desktop.
This is a template prototype for the Facebook Pixel.
// Create Permissions
const copy = require('copyFromWindow');
const set = require('setInWindow');
const alias = require('aliasInWindow');
const queue = require('createQueue');
const call = require('callInWindow');
const map = require('makeTableMap');
const log = require('logToConsole');
const script = require('injectScript');
const initIds = copy('_fbq_gtm_ids') || [];
const pixelIds = data.pixelId;
// Utility function to use either fbq.queue[]
// (if the FB SDK hasn't loaded yet), or fbq.callMethod()
// if the SDK has loaded.
function getFbq() {
// Return the existing 'fbq' global method if available
let fbq = copy('fbq');
if (fbq) {
return fbq;
}
// Initialize the 'fbq' global method to either use
// fbq.callMethod or fbq.queue)
set('fbq', function() {
const callMethod = copy('fbq.callMethod.apply');
if (callMethod) {
call('fbq.callMethod.apply', null, arguments);
} else {
call('fbq.queue.push', arguments);
}
});
alias('_fbq', 'fbq');
// Create the fbq.queue
queue('fbq.queue');
// Return the global 'fbq' method, created above
return copy('fbq');
}
// Get reference to the global method
const fbq = getFbq();
// Build the fbq() command arguments
const props = data.propertyList ? map(data.propertyList, 'name', 'value') : {};
const command = data.eventName !== 'Custom' ? 'trackSingle' : 'trackSingleCustom';
const eventName = data.eventName !== 'Custom' ? data.eventName : data.customEventName;
// Handle multiple, comma-separated pixel IDs,
// and initialize each ID if not done already.
pixelIds.split(',').forEach(function(pixelId) {
if (initIds.indexOf(pixelId) === -1) {
// If the user has chosen to disable automatic configuration
if (data.disableAutoConfig) {
fbq('set', 'autoConfig', false, pixelId);
}
// Initialize pixel and store in global array
fbq('init', pixelId);
initIds.push(pixelId);
set('_fbq_gtm_ids', initIds, true);
}
// Call the fbq() method with the parameters defined earlier
fbq(command, pixelId, eventName, props);
});
// Log & Signal Success
const onSuccess = () => {
log('Facebook script loaded successfully.');
data.gtmOnSuccess();
};
// Log & Signal Failure
const onFailure = () => {
log('Facebook script load failed.');
data.gtmOnFailure();
};
script('https://connect.facebook.net/en_US/fbevents.js', onSuccess, onFailure, 'fbPixel');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment