Last active
          June 26, 2018 19:37 
        
      - 
      
 - 
        
Save camshaft/acf8e9e0b4cc55812bd6 to your computer and use it in GitHub Desktop.  
    multiple google experiments
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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(); | |
| } | 
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
  
            
Nice!
One thing I noted:
cb(cxApi.chooseVariation());does not seem to work - at least in the current version of Chrome - butcb(this.cxApi.chooseVariation());does work.