design document for Chrome's user script's implementation 提到了这些已知问题:
- Chromium 不支持
@require、@resource、unsafeWindow、GM_registerMenuCommand、GM_setValue 或 GM_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 处的脚本加载到文档中。可选地,可以为onLoad 和onError 提供回调。
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)})};