在开发这个小用户时我遇到了一个问题.当我想XMLHttpRequest用我的脚本阻止正在运行的网站中的每一个时,没有发生任何事情(至少在Chrome上):
function main() {
// Override XHR.open with a custom function
window.XMLHttpRequest.prototype.open = function() {
// Nothing... so it's supposed to block every xhr.open() call
}
}
main();
Run Code Online (Sandbox Code Playgroud)
更换时同样的事情window的unsafeWindow.
然而,当我使用这个小技巧时,一切都像魅力一样:
// No more call to main(), and:
var script = document.createElement("script");
script.textContent = "(" + main.toString() + ")();";
document.body.appendChild(script);
Run Code Online (Sandbox Code Playgroud)
每次调用xhr.open都被我的自定义函数替换,不再需要AJAX.
所以我猜这个window元素在main从脚本内部调用时与从<script></script>容器中调用时的元素不同.有人能解释一下为什么吗?
我在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设置的变量,反之亦然?