设置@grant值时如何访问`window`(目标页面)对象?

时间:2014-09-11 03:16:27

标签: javascript firefox greasemonkey

假设我正在使用以下网页:

<html>
<body>
<span id="click">click me</span>
<script>
var hello = function() {
    alert('hello');
}

document.getElementById('click').addEventListener('click', function(e) {
    hello();
});
</script>
</body>
</html>

我的Greasemonkey脚本是:

// ==UserScript==
// @name        My Script
// @include     http://example.com/hello.html
// @version     1
// @grant       none
// ==/UserScript==

window.hello = function() {
    alert('goodbye');
}

禁用Greasemonkey脚本后,单击页面上的#click元素会显示“hello”警告。启用脚本后,单击该元素将显示“再见”警报。

足够简单。网页中的hello函数正在被Greasemonkey脚本中的函数替换。

现在假设我想使用Greasemonkey API。当我将@grant值设置为除'none'之外的有效值(例如// @grant GM_setClipboard)[导致Greasemonkey将脚本作为“内容脚本”运行,而不是在页面的范围内'无'],Greasemonkey脚本无效。

window.hello不再定位到网页上的正确对象。

window.hello替换unsafeWindow.hello看起来会起作用,但JS控制台中会抛出以下错误:

  

错误:拒绝访问对象的权限

如何在@grant GM_setClipboard设置为定位并替换页面上的原始hello功能的同时重写Greasemonkey脚本?

系统信息:

  • Windows 7 64位
  • Firefox 32.0
  • Greasemonkey 2.2

2 个答案:

答案 0 :(得分:16)

当您设置{none}之外的@grant值时,Greasemonkey会激活其沙箱和Greasemonkey 2.0 radically changed unsafeWindow handling

现在,为了在目标页面范围内创建或覆盖变量,您必须从技术菜单中正确选择。 EG:

阅读:

  • 一个简单的变量:

    Target page sets:       var foo = "bar";
    GM script can read:     unsafeWindow.foo    //-- "bar"
    
  • 一个简单的对象:

    Target page sets:       var obj = {A: 1};
    GM script can read:     unsafeWindow.obj    //-- Object { A: 1 }
    
  • 一个复杂的对象:这并非总是可行。

致电:

  • 一个简单的功能:

    Target page sets:       function func () {console.log ('Hi');}
    GM script can call:     unsafeWindow.func() //-- "Hi"
    
  • 复杂功能: This is not always possible.

写入/设置:

  • 一个简单的变量:

    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 ();
} );

你可以在this jsFiddle page看到。

如果您针对该页面安装并运行此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脚本能够读取和更改页面的变量和功能。


注意:

  1. 这都是 Firefox特定的
  2. 对于跨平台代码,对于某些复杂情况,您可以使用Script Injection代替。但注入的代码无法直接访问GM_函数。
  3. 请注意,这些技术仅适用于全局的javascript变量和函数。

答案 1 :(得分:0)

将代码包装在lambda函数中,例如:

(function(window){      // and more arguments if you need it

  console.log(window);  // here, should be the real 'window'

})(window.unsafeWindow)