Created
January 8, 2015 19:26
-
-
Save bradvogel/cff0935f91734d119273 to your computer and use it in GitHub Desktop.
Segment events bridge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Provides a fake analytics object that sends all calls to the analytics bridge. Why do we use | |
* an analytics bridge? Well, we can't load Segment's analytics snippet in this extension source or | |
* in the chrome extension content script because it will conflict with the Gmail DOM. By loading a standalone file (hosted | |
* by the app), we can sandbox Segment and its dependencies away from Gmail, while providing a | |
* postMessage bridge to be able to call its methods. | |
*/ | |
var analytics = (function() { | |
var loaded = false; | |
var eventQueue = []; | |
var iframe = $('<iframe style="display:none" src="analyticsbridge.html"></iframe>') | |
.on('load', function() { | |
loaded = true; | |
flush(); | |
}); | |
$(document.body).append(iframe); | |
// Send the events to the frame if it's ready. | |
function flush(method, args) { | |
if (!loaded) return; | |
while (eventQueue.length) { | |
var evt = eventQueue.shift(); | |
iframe[0].contentWindow.postMessage({ | |
method: evt[0], | |
arguments: evt[1] | |
}, '*'); | |
} | |
} | |
var analyticsProxy = {}; | |
// List of methods from the snippet at https://segment.com/docs/libraries/analytics.js/quickstart/ | |
// and also added 'load'. | |
var methodsToProxy = [ | |
'trackSubmit', | |
'trackClick', | |
'trackLink', | |
'trackForm', | |
'pageview', | |
'identify', | |
'group', | |
'track', | |
'ready', | |
'alias', | |
'page', | |
'once', | |
'off', | |
'on', | |
'load' | |
]; | |
methodsToProxy.forEach(function(method) { | |
analyticsProxy[method] = function( /* Variable arguments */ ) { | |
eventQueue.push([method, _.toArray(arguments)]); | |
flush(); | |
}; | |
}); | |
return analyticsProxy; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment