Ale*_*lex 7 javascript greasemonkey google-chrome cross-browser userscripts
有一个页面http://example.com/1.php像往常一样包含javascript文件:
<script type="text/javascript" src="/util.js?1354729400"></script>
Run Code Online (Sandbox Code Playgroud)
这个文件包含名为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!");
}
Run Code Online (Sandbox Code Playgroud)
在Firefox中完美运行并在Chrome中返回错误:
Uncaught ReferenceError: exampleFunction is not defined
Run Code Online (Sandbox Code Playgroud)
我如何使其工作?
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9338 次 |
| 最近记录: |