javascript - window.onload 在 Firefox+Greasemonkey 脚本中有效,但在 Chrome 用户脚本中无效?

标签 javascript google-chrome cross-browser greasemonkey userscripts

有一个页面http://example.com/1.php像往常一样包含 javascript 文件:

<script type="text/javascript" src="/util.js?1354729400"></script>

此文件包含名为 exampleFunction 的函数,我需要在我的用户脚本中使用它。 我还有一个用户脚本:

// ==UserScript==
// @name          SomeName
// @namespace     http://example.com/userscripts
// @description   Greets the world
// @include       http://example.com/*
// ==/UserScript==
window.onload = function () {
        console.log(exampleFunction);
      alert("LOADED!");
}

在 Firefox 中完美运行,在 Chrome 中返回错误:

Uncaught ReferenceError: exampleFunction is not defined 

如何让它发挥作用?

最佳答案

exampleFunction 未定义的原因是因为 Chrome 用户脚本在沙箱 ("isolated world") 中运行。请注意,Greasemonkey 脚本也经常在沙箱中运行,但您的脚本当前使用an implicit @grant none 运行。 .
如果您的脚本要使用 GM_ 函数,它也会在 Firefox 中停止工作。

要使此脚本在两种浏览器(以及其他一些浏览器)上运行,请使用脚本注入(inject) similar to this answer .

但是,还有另一个障碍,因为该脚本正在使用 window.onloadChrome userscripts, with the default execution start-mode, will often never see the onload event.

要解决这个问题,请添加 // @run-at document-end到元数据 block 。

所以脚本变成:

// ==UserScript==
// @name            SomeName
// @namespace       http://example.com/userscripts
// @description     Greets the world
// @include         http://example.com/*
// @run-at          document-end
// @grant           none
// ==/UserScript==

function GM_main () {
    window.onload = function () {
        console.log(exampleFunction);
        alert("LOADED!");
    }
}

addJS_Node (null, null, GM_main);

//-- This is a 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);
}

关于javascript - window.onload 在 Firefox+Greasemonkey 脚本中有效,但在 Chrome 用户脚本中无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13731209/

相关文章:

CSS - 字体在 Firefox 和 Chrome 中呈现不同

javascript - jquery - 文档就绪未触发

css - 在 Chrome 中启用透视 CSS 转换?

javascript - 图像预览在 Safari 中不起作用

javascript - 当我使用 Javascript 重新加载表单时,我无法保留之前保存的弹出表单数据 - jointJS

javascript - 单元测试 Angular Directive(指令)

javascript - 延迟加载 JavaScript - 未捕获的 ReferenceError : $ is not defined

javascript - 将文本连接到具有特定数据属性值的选项

html - 溢出 :hidden not working with border-radius in Chrome

asp.net - 旧版 Web 应用程序 - 确定与现代浏览器的向前兼容性?