Javascript variable scope in a JS URI, or how to write page-scope objects?

大城市里の小女人 提交于 2019-12-02 04:39:29

In Chrome, there is a delay after the location.assign calls (they may run in separate threads), so the tutu var isn't defined when the alert() fires and the whole code throws an exception. (Also, as trinity said, the alert needs to be prefaced with javascript:.)

You could use a timer like so:

location.assign("javascript:var tutu = 'oscar';");
setTimeout (
    function () {location.assign("javascript:console.log('1:' + tutu);"); }
    , 666
);

But, I think you'll agree that's a spot of bother.

Trying to do page-scope javascript with location.assign will get cumbersome for all but the shortest/simplest code.

Set, reset, and/or run lots of page-scope javascript using Script Injection:

function setPageScopeGlobals () {
    window.tutu     = 'Oscar';
    window.globVar2 = 'Wilde';
    window.globVar3 = 'Boyo';

    alert ('1:' + tutu);

    window.useGlobalVar = function () {
        console.log ("globVar2: ", globVar2);   
    };
}

//-- Set globals
addJS_Node (null, null, setPageScopeGlobals);

//-- Call a global function
addJS_Node ("useGlobalVar();");

//-- Standard-ish utility function:
function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    if (runOnLoad) {
        scriptNode.addEventListener ("load", runOnLoad, false);
    }
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!