Search code examples
javascriptvar

How to get a JavaScript variable?


From a page containing (or referring to) my JavaScript I do an AJAX XHR request to an external Web site.

The external Web site return on our GET request a JavaScript file like this:

var __xxx = {
    // ....
};

How do I get the value of the variable __xxx in my JavaScript?

Currently, the only way I invented is to remove var __xxx using a regular expression and parse the remaining using a JSON parser. Is there a better way?

The external Web site may be considered as trusted if necessary, but I would prefer not to trust the data from it (using some safe parser like JSON).


Solution

  • Create a new function utilizing strings and the Function constructor. Add 'return _xxx;' and assign the result to a new variable that is accessible in your current script.

    var returned_data = new Function(data + " return _xxx;")()
    

    This is preferable to eval because the execution of the function will not allow access to local variables outside of the function scope.