【问题标题】:Why doesn't jQuery work in Chrome user scripts (Greasemonkey)? [duplicate]为什么 jQuery 在 Chrome 用户脚本 (Greasemonkey) 中不起作用? [复制]
【发布时间】:2011-02-05 00:30:24
【问题描述】:

可能重复:
How can I use jQuery in Greasemonkey scripts in Google Chrome?

我无法让此用户脚本在 Google Chrome 中运行。

// ==UserScript==
// @name           voip
// @namespace      1
// @description    voip
// @include        *
// @require        http://jquery.com/src/jquery-latest.js
// ==/UserScript==

$(document).ready(function() {  
        alert("Hello world!");
});

警报不显示。如果我只是在脚本中输入alert("Hello world!");,它就可以工作。

如何在 Chrome 用户脚本中使用 jQuery?

【问题讨论】:

    标签: jquery google-chrome userscripts


    【解决方案1】:

    design document for Chrome's user script's implementation 提到了这些已知问题:

    • Chromium 不支持 @require@resourceunsafeWindowGM_registerMenuCommandGM_setValueGM_getValue
    • GM_xmlhttpRequest 仅同源。

    这在问题Include Jquery inside GreaseMonkey script under Google Chrome 中得到解决。这里是my answer from that question


    我已经基于来自Erik Vold's answer 的脚本编写了一些函数来帮助我在文档中运行函数、代码和其他脚本。您可以使用它们将 jQuery 加载到页面中,然后在全局 window 范围内运行代码。

    示例用法

    // ==UserScript==
    // @name           Example from https://stackoverflow.com/q/6825715
    // @version        1.2
    // @namespace      https://stackoverflow.com/q/6825715
    // @description    An example, adding a border to a post on Stack Overflow.
    // @include        https://stackoverflow.com/questions/2588513/*
    // ==/UserScript==
    
    var load,execute,loadAndExecute;load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},loadAndExecute=function(a,b){return load(a,function(){return execute(b)})};
    
    loadAndExecute("//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
        $("#answer-6825715").css("border", ".5em solid black");
    });
    

    您可以click here 安装它,如果您相信我没有试图欺骗您安装恶意软件,并且没有人编辑我的帖子以指向其他内容。重新加载页面,您应该会在我的帖子周围看到一个边框。

    功能

    load(url, onLoad, onError)

    url 处的脚本加载到文档中。可选地,可以为onLoadonError 提供回调。

    execute(functionOrCode)

    在文档中插入一个函数或代码字符串并执行它。这些函数在插入之前会转换为源代码,因此它们会失去当前的作用域/闭包,并在全局 window 作用域下运行。

    loadAndExecute(url, functionOrCode)

    快捷方式;这会从url 加载一个脚本,如果成功则插入并执行functionOrCode

    代码

    源 CoffeeScript

    我在 CoffeeScript (a little language that compiles to JavaScript) 中编写了这些内容。这是供您自己使用 CofeeScript 的 CoffeeScript 源。对于 JavaScript 用户,编译和缩小的代码包含在下面。

    load = (url, onLoad, onError) ->
        e = document.createElement "script"
        e.setAttribute "src", url
    
        if onLoad? then e.addEventListener "load", onLoad
        if onError? then e.addEventListener "error", onError
    
        document.body.appendChild e
    
        return e
    
    execute = (functionOrCode) ->
        if typeof functionOrCode is "function"
            code = "(#{functionOrCode})();"
        else
            code = functionOrCode
    
        e = document.createElement "script"
        e.textContent = code
    
        document.body.appendChild e
    
        return e
    
    loadAndExecute = (url, functionOrCode) ->
        load url, -> execute functionOrCode
    

    编译和缩小的 JavaScript(468 个字符)

    var load,execute,loadAndExecute;load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},loadAndExecute=function(a,b){return load(a,function(){return execute(b)})};
    

    【讨论】:

      【解决方案2】:

      【讨论】:

      【解决方案3】:

      Chrome 中的 Greasemonkey 支持不包括 require 语句。你最好创建一个 extension 而不是 Greasemonkey 脚本。

      那个,或者你可以使用 Google API 来加载 jQuery。

      【讨论】:

      • 会做 document.getElementsByTagName('head')[0].appendChild(GM_JQ);工作吗?
      • 如果 GM_JQ 是一个包含指向 jQuery 的链接的脚本元素,那么肯定会起作用。
      【解决方案4】:

      简单的解决方案(如果对您可行)就是将缩小版的 jQuery 复制粘贴到您的greasemonkey 脚本中。

      // ==UserScript==
      // @name           voip
      // @namespace      1
      // @description    voip
      // @include        *
      // ==/UserScript==
      //jQuery 1.4.2 minified code
      (function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll...
      ....
      A.jQuery=A.$=c})(window);
      //your code
      $(document).ready(function() {  
          alert("Hello world!");
      });
      

      【讨论】:

      • 将 jQuery 代码缓存一次会比使用它的每个脚本更有效。
      • 我知道。你有更好的解决方案吗?
      • 你确定这有效吗?我试过了,但从未收到“Hello World”警报。 (火狐 3.6)
      • 不,我不确定这是否有效。我没有尝试。顺便提一句。该解决方案适用于 chrome。不适用于无论如何都支持 @require 的 Firefox
      【解决方案5】:

      只需使用Content Script 创建一个 Chrome 扩展程序。很简单:

      ma​​nifest.json

      {
        "name": "Hello World",
        "version": "1.0",
        "description": "Greets the world",
        "content_scripts": [
          {
            "matches": ["*"],
            "css": ["main.css"],
            "js": ["jquery.min.js","main.js"],
            "run at":"document_end",
          }
        ]
      }
      

      ma​​in.js

      $(document).ready(function(){
          alert('Hello World');
      });
      

      值得指出的是,在此示例中,实际上不需要将警报包装在 $(document).ready() 中,因为清单文件已经指定脚本应为 "run at" : "document_end"

      此外,正如您将在文档中看到的那样,jquery.min.js 和 main.js 必须与 manifest.json 包含在同一文件夹中

      【讨论】:

      • "run at":"document_end" 后面有一个逗号。
      【解决方案6】:

      尝试使用TamperMonkey

      您的脚本按原样为我工作,并且我制作了许多其他使用 jQuery 的用户脚本。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-18
        • 1970-01-01
        • 1970-01-01
        • 2015-10-14
        相关资源
        最近更新 更多