相关疑难解决方法(0)

从Greasemonkey访问变量到页面,反之亦然

我在test.js中有以下代码,它在</ body>之前运行:

alert('stovetop');
alert(greasy);
Run Code Online (Sandbox Code Playgroud)

我在test.user.js中有以下代码:

(function () {

    'use strict';
    var greasy = 'greasy variable';
    document.title = 'greasy title';

}());
Run Code Online (Sandbox Code Playgroud)

'炉灶'得到警报,所以我知道页面javascript工作,并document.title得到更改,所以我知道脚本javascript工作.但是,在网页上我收到错误:

错误:ReferenceError:未定义greasy源文件:/test.js

如何从网页上访问由Greasemonkey设置的变量,反之亦然?

javascript firefox greasemonkey firefox-addon

9
推荐指数
1
解决办法
2万
查看次数

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

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

<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>
Run Code Online (Sandbox Code Playgroud)

我的Greasemonkey脚本是:

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

window.hello = function() {
    alert('goodbye');
}
Run Code Online (Sandbox Code Playgroud)

禁用Greasemonkey脚本后,单击#click页面上的元素将显示"hello"警报.启用脚本后,单击该元素将显示"再见"警报.

很简单.在hello从网页的功能正在由Greasemonkey的脚本功能所取代.

现在让我们说我想使用Greasemonkey API.当我将@grant值设置为除'none'之外的有效值(例如// @grant GM_setClipboard)[导致Greasemonkey将脚本作为"内容脚本"运行时,而不是像'none'那样在页面的范围内运行),Greasemonkey脚本无法工作.

window.hello 不再定位页面上的正确对象.

更换window.hellounsafeWindow.hello看起来像它的工作,而是下面的错误是在JS控制台抛出:

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

如何在@grant GM_setClipboard设置目标并替换hello页面上的原始函数时重写Greasemonkey脚本?

系统信息:

  • Windows 7 64位
  • Firefox 32.0 …

javascript firefox greasemonkey

5
推荐指数
1
解决办法
6030
查看次数

标签 统计

firefox ×2

greasemonkey ×2

javascript ×2

firefox-addon ×1