的快速和骯髒的方式做到這一點,如果你不需要任何GM_
功能你不@require
自己的jQuery,就是用@grant none
模式。這工作:
// ==UserScript==
// @name _unsafeWindow tests
// @include http://jsbin.com/xaman/*
// @grant none
// ==/UserScript==
var jQuery = window.jQuery;
jQuery(document).bind ("MyEvent", function() {
console.log ("From GM script: MyEvent caught!");
});
如果您確實需要GM_
功能,您可以有時使用the new exportFunction()
。
不幸的是,jQuery和jQuery事件處理是一個特例。根據你嘗試一下,你會得到錯誤信息,如:
權限被拒絕訪問屬性「處理」
或
CloneNonReflectorsWrite錯誤
我只是發現沒有辦法做到這一點使用任何新的unsafeWindow
功能。你唯一的辦法是注入代碼。像這樣:
// ==UserScript==
// @name _unsafeWindow tests
// @include http://jsbin.com/xaman/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
function myEventHandler (zEvent) {
console.log (
'From GM script: "' + zEvent.type + '" triggered on ', zEvent.target
);
}
function bindMyEvent() {
//-- Gets "jQuery is not defined" if GM script does not also use jQuery.
jQuery(document).bind ("MyEvent", myEventHandler);
console.log ("The jQuery version being used is: ", jQuery.fn.jquery);
}
//-- Create A COPY OF myEventHandler in the target page scope:
addJS_Node (myEventHandler);
//-- Create A COPY OF bindMyEvent in the target page scope and immediately run it.
addJS_Node (null, null, bindMyEvent);
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);
}
如果你需要運行/從注入的事件處理程序(一個或多個)中調用GM_
功能,在「How to call Greasemonkey's GM_ functions from code that must run in the target page scope?」顯示使用技巧。
我不確定OP是否真的談論GreaseMonkey - 鏈接的博文是關於附加SDK中的內容腳本的。 –
@WladimirPalant,這是因爲Greasemonkey 2.0複製了SDK更改,並引用了該SDK博客文章中的解決方法。參見[Greasemonkey 2.0公告](http://www.greasespot.net/2014/06/greasemonkey-20-release.html)。大多數GM用戶可以通過恢復到之前的GM版本來暫時修復這些不安全的窗口問題 - 至少FF 30。 –
OP正在討論GreaseMonkey! @BrockAdams真棒!第二個剪輯是一種怪物,但我必須在這裏維護這個腳本。奇蹟般有效。非常感謝你! – Reini