javascriptexternalinterface

Set variable with function


I'm trying to use ExternalInterface to modify an HTML page, but it is only able to call Javascript functions and not set variables. What I want to do is set a variable with a function, like doing set_var('foo','bar') would be equivalent to var foo='bar'. In PHP, I could make a function like:

function set_var($varname, $value)
{
    $GLOBALS[$varname]=$value;
}

But I don't know how to do this in Javascript. Maybe something with the window object?


Solution

  • You were on the right path with the window object for accessing global variables in javascript via a string that contains the name of the variable.

    function set_var(varname, value) {
        window[varname] = value;
    }
    

    In javascript, you can use [] to access properties on an object. If the name of the property is in a variable, this is the only way (other than using eval()) to access the property name. Since global variables are properties on the window object in browser-javascript that's why this works.