【问题标题】:Javascript variable scope in a JS URI, or how to write page-scope objects?JS URI 中的 Javascript 变量范围,或者如何编写页面范围对象?
【发布时间】:2012-11-29 02:14:15
【问题描述】:

我正在编写一个尝试在 Chrome 和 Firefox 中使用的 Greasemonkey 脚本。我知道您不能像在 Firefox 中那样在 Chrome 中使用 unsafewindow,所以我一直在尝试使用 jS-uris,例如:Greasemonkey, Chrome and unsafeWindow.foo()

当我尝试以下操作时:

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

我收到一条错误消息,显示“tutu”未定义。显然我不明白的是这些变量的范围。我需要为我正在做的事情创建全局函数和变量。我做错了什么?

编辑:实际上我认为问题不是我正在尝试的(除非它是,在这种情况下请告诉我)但是我正在为外观编写脚本的页面与 URLS 混淆以阻止它们继续除了相对 URI 之外的任何内容。

【问题讨论】:

    标签: javascript cross-browser greasemonkey scope userscripts


    【解决方案1】:

    在 Chrome 中,location.assign 调用后会有延迟(它们可能在单独的线程中运行),因此当alert() 触发并且整个代码引发异常时,tutu 变量未定义。 (另外,正如三位一体所说,alert 需要以javascript: 开头。)

    你可以像这样使用计时器:

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

    但是,我想你会同意这很麻烦。

    尝试使用 location.assign 执行页面范围的 javascript 会变得很麻烦,除了最短/最简单的代码。

    使用 Script Injection 设置、重置和/或运行 lots 页面范围的 javascript:

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

    【讨论】:

    • 它运行良好,而且运行良好。我一直在寻找(字面意思)日日夜夜。谢谢你,非常感谢。 nani gigantum humeris insidentes
    猜你喜欢
    • 2013-05-29
    • 1970-01-01
    • 2012-01-21
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2012-04-09
    相关资源
    最近更新 更多