Rich-text Reply

How to change a javascript variable

stefank 10-16-14
Accepted Solution

How to change a javascript variable



I am running into the problem where my namespaced javascript variables do not exist when optimizely fires, and thus it can't change them.


I have tried writing js code to detect whether the variable is finally defined (using timeouts to wait) and via the activator settings, however neither of them work -- I've been testing these via the url overrides you can pass in.


Any pointers appreciated.






Level 2

stefank 10-17-14

Re: How to change a javascript variable

Figured it out. Needed to reference the variable with "window" prepended to it.
Level 2
stefank 10-17-14

Re: How to change a javascript variable

JDahlinANF 10-30-14

Re: How to change a javascript variable

A slight modifcation to the function posted in this article solves the issue.

Where the original function looks for an element to exist (the length of the CSS selector is greater than zero), to detect if a variable exists, you can look for "typeof is not undefined".


In this example, I am looking for the existence of the variable "someNameSpace.customVariableHere" and setting the value to "Found It" once it exists.  For this example, I use a namespaced variable, but this could just as easily be "window.variableHere" instead.  I use the namespaced variable because this required some additional logic so as to not throw unwanted errors in the user's browser console.


function waitForDelayedContent(selector, experiment, timeout, keepAlive) {
    var intervalTime = 50;
    var timeout = timeout || 3000;
    var keepAlive = keepAlive || false;
    var maxAttempts = timeout / intervalTime;
    var attempts = 0;
    var interval = setInterval(function() {
        var selectorVal = (function(){
            try {
                return eval(selector);
            } catch(e) {
                return undefined;
        if (typeof selectorVal !== 'undefined') {
            if (!keepAlive) {
        } else  if (attempts > maxAttempts) {
        attempts ++;
    }, intervalTime);

waitForDelayedContent("window.someNameSpace.customVariableHere", function(){
  window.someNameSpace.customVariableHere = "Found It";


To test this, I added some code to my webpage that does:

var someNameSpace.customVariableHere = "";

Then, using the optimizely_x parameters verified that the value is empty for =0 and contains the value "Found It" for =1.