当您设置@grant
除 none 以外的值时,Greasemonkey 会激活其沙箱,并且Greasemonkey 2.0 彻底改变了 unsafeWindow 处理。
现在,为了在目标页面范围内创建或覆盖变量,您必须从技术菜单中正确选择。例如:
读书:
致电:
写入/设置:
一个简单的变量:
unsafeWindow.foo = "Apple";
一个简单的对象:
var gmObject = {X: "123"};
unsafeWindow.obj = cloneInto (gmObject, unsafeWindow);
一个简单的函数:
function gmFunc () {
console.log ("Lorem ipsum");
//-- Can use GM_ functions in here! :)
}
unsafeWindow.func = exportFunction (gmFunc, unsafeWindow);
考虑这个 HTML:
<button id="helloBtn">Say "Hello".</button>
这个javascript:
var simpleGlobalVar = "A simple, global var in the page scope.";
var globalObject = {Letter: "A", Number: 2};
function simpleFunction () {
console.log ("The target page's simpleFunction was called.");
}
var sayHello = function() {
console.log ('Hello.');
}
document.getElementById ('helloBtn').addEventListener ('click', function () {
sayHello ();
} );
您可以在此 jsFiddle 页面上实时查看。
如果您针对该页面安装并运行此 Greasemonkey 脚本:
// ==UserScript==
// @name _Demonstrate accessing target-page variables with @grant values set
// @include http://fiddle.jshell.net/sepwL7n6/*/show/
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
console.log ("*** Greasemonkey script start.");
$("body").append ('<div id="gmArea">Added by Greasemonkey:<p></p></div>');
$("#gmArea > p:first").append ('<button id="gmShow">Access select target-page variables and functions</button>');
$("#gmArea > p:first").append ('<button id="gmChange">Change javascript things in the target-page scope.</button>');
$("#gmShow").click ( function () {
//-- Access things from the target-page scope:
console.log ("----------------");
console.log ("==> simpleGlobalVar is: ", unsafeWindow.simpleGlobalVar);
console.log ("==> globalObject is: ", unsafeWindow.globalObject);
console.log ("==> Calling target's simpleFunction():");
unsafeWindow.simpleFunction ();
//-- WARNING! This next technique is not robust, but works in some cases.
console.log ("==> Calling target's button's click().");
unsafeWindow.document.getElementById ('helloBtn').click ();
} );
$("#gmChange").click ( function () {
this.disabled = true; //-- Can only click once.
unsafeWindow.simpleGlobalVar = "Simple var... Intercepted by GM!";
unsafeWindow.globalObject = cloneInto (gmObject, unsafeWindow);
unsafeWindow.sayHello = exportFunction (sayHello, unsafeWindow);
console.log ("==> Target page objects were changed.");
} );
var gmMessageStr = "Function... Intercepted by GM, but also can use GM_ functions!";
function sayHello () {
sayHello.K = (sayHello.K || 0) + 1;
console.log (gmMessageStr);
GM_addStyle ('body {background: ' + (sayHello.K % 2 ? "lime" : "white") + ';}');
}
var gmObject = {message: "Object overridden by GM."};
打开控制台并按下按钮,您将看到 GM 脚本能够读取和更改页面的变量和函数。
笔记:
- 这都是Firefox 特有的。
- 对于跨平台代码,以及一些复杂的情况,你可以使用脚本注入来代替。但是注入的代码不能直接访问
GM_
函数。
- 请注意,这些技术仅适用于全局的 javascript 变量和函数。