Javascript variable scope in a JS URI, or how to w

2020-04-21 03:46发布

问题:

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 been attempting to use jS-uris like in the answer for: Greasemonkey, Chrome and unsafeWindow.foo().

when I try the following:

location.assign("javascript:var tutu = 'oscar';");
location.assign("alert('1:' + tutu);");
alert('2:' + tutu);

I receive an error showing that "tutu" is undefined. Obviously what I'm not understanding is the scope of these variables. I need to make global functions and variables for what I'm working on. What am I not doing correctly?

EDIT: Actually I think the problem isn't what I'm trying (unless it is, in which case please tell me) but the page I'm writing the script for looks is messing with URLS to keep them from going to anything but a relative URI.

回答1:

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