我在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设置的变量,反之亦然?
假设我正在使用以下网页:
<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.hello用unsafeWindow.hello看起来像它的工作,而是下面的错误是在JS控制台抛出:
错误:拒绝访问对象的权限
如何在@grant GM_setClipboard设置目标并替换hello页面上的原始函数时重写Greasemonkey脚本?
系统信息: