Skip to content

Instantly share code, notes, and snippets.

@camshaft
Last active June 26, 2018 19:37
Show Gist options
  • Save camshaft/acf8e9e0b4cc55812bd6 to your computer and use it in GitHub Desktop.
Save camshaft/acf8e9e0b4cc55812bd6 to your computer and use it in GitHub Desktop.
multiple google experiments
function choose(id, cb) {
var i = document.createElement('iframe');
i.setAttribute('sandbox', 'allow-scripts allow-same-origin');
document.body.appendChild(i);
var win = i.contentWindow.window;
win.loaded = function() {
cb(cxApi.chooseVariation());
};
var doc = win.document;
doc.open();
doc.write('<script src="//www.google-analytics.com/cx/api.js?experiment=' + id+ '"></script><script>window.loaded();</script>');
doc.close();
}
@onderweg
Copy link

Nice!

One thing I noted: cb(cxApi.chooseVariation()); does not seem to work - at least in the current version of Chrome - but cb(this.cxApi.chooseVariation()); does work.

@mihalik
Copy link

mihalik commented Jan 14, 2016

If anyone stumbles across this, just FYI that the above does not work in IE. I had to use frame.src = 'javascript:window["contents"]'; to get it the content into the frame. My code ended up looking something like this:

  const frame = document.createElement('iframe');
  const content = '<script src="//www.google-analytics.com/cx/api.js?experiment=' + experimentId + '"></script>';
  frame.src = 'javascript:window["contents"]';
  frame.setAttribute('sandbox', 'allow-scripts allow-same-origin');
  frame.style.display = 'none';
  frame.onload = function() {
    const cxApi = frame.contentWindow.cxApi;
    if (cxApi) {
      cb(cxApi.chooseVariation());
    }
  };
  document.body.appendChild(frame);
  frame.contentWindow.contents = content;
  const doc = frame.contentWindow.document;
  if (!doc.scripts.length) {
    doc.open();
    doc.write(content);
    doc.close();
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment