javascript – window.onload在Firefox Greasemonkey脚本中有效但在Chrome用户脚本中无效吗?

一个页面 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中运行.

要使此脚本在两个浏览器(以及其他一些浏览器)上运行,请使用脚本注入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添加到元数据块.

所以脚本变成:

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...