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

前端 未结 1 1800
庸人自扰
庸人自扰 2021-01-24 11:01

I\'m writing a Greasemonkey script that I\'m trying to use in Chrome and Firefox. I know you can\'t use unsafewindow in Chrome like you can in Firefox, so I\'ve bee

1条回答
  •  孤城傲影
    2021-01-24 11:05

    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);
    }
    

    0 讨论(0)
提交回复
热议问题