且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

添加@grant值会破坏我的Greasemonkey + jQuery脚本吗?

更新时间:2023-12-05 21:02:04

请参见错误:拒绝访问属性'handler'的权限" .

您不能再像这样调用目标页面的jQuery.

You can no longer invoke the target-page's jQuery like that.

(请注意,在@grant none模式下(GM 2的默认设置),unsafeWindowwindow相同……但是,您不能使用GM_函数.)

(Note that in @grant none mode (the default as of GM 2), unsafeWindow is the same as window... But, then you can't use GM_ functions.)

@require您自己的jQuery副本;它不会与页面冲突,并且加载速度会更快.

@require your own copy of jQuery; it will not conflict with the page's and will load faster, to boot.

请勿将unsafeWindow用于此类操作(或者,如果可以的话,请完全使用),并且Greasemonkey脚本几乎也不需要$(document).ready().

Do not use unsafeWindow for things like this (or at all, if you can help it), and $(document).ready() is also almost never needed for Greasemonkey scripts.

您的(新的)示例脚本将仅仅是:

Your (new) sample script would merely be:

// ==UserScript==
// @name        Dimi Test
// @namespace   Dimi
// @version     1
// @grant       GM_xmlhttpRequest
// @include     about:addons
// @include     http://*.myDomain.*/*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// ==/UserScript==

$("body").prepend ('<h1>Hello World!</h1>');

然后您可以毫无问题地将GM_函数和jQuery实例混合使用.

And you can then mix GM_ functions and your instance of jQuery with no problems.

注意:问题脚本具有// @include about:addons.
按设计,Greasemonkey脚本将无法在about:addons页面上使用.

Note: The question script has // @include about:addons.
Greasemonkey scripts will not work on the about:addons page, by design.