![](/img/trans.png)
[英]Userscript works in Chrome/Tampermoney but not in Firefox/Greasemonkey
[英]window.onload works in Firefox+Greasemonkey script but not in a Chrome userscript?
有一个页面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用户脚本在沙箱中运行( “孤立世界” )。 请注意,Greasemonkey脚本通常也在沙箱中运行,但是您的脚本当前正在使用隐式@grant none
运行。
如果您的脚本使用GM_
函数,它也将停止在Firefox中运行。
要使此脚本在两个浏览器(以及其他一些浏览器)上运行,请使用类似于此答案的 脚本注入 。
但是 ,还有另一个问题,因为该脚本使用的是window.onload
。 使用默认执行启动模式的Chrome用户脚本通常永远不会看到onload
事件。
要解决这个问题,请将// @run-at document-end
到元数据块。
所以脚本变成:
// ==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);
}
如果你想要等同于onLoad
,它在页面上的所有图像都被加载之前不会触发,你想在元数据块中使用// @run-at document-idle
。 加载DOM时会触发默认的document-end,相当于document.ready。
你试过用括号调用examplefunction吗? :) 像这样:
console.log(exampleFunction());
如果您在chrome控制台中尝试它,则必须为调用函数添加括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.