有一个页面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.onload
。 Chrome 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/