[英]Adding @grant to a GM script breaks the overload of XMLHttpRequest.prototype.open?
我正在编写一个Greasemonkey脚本,我想在其中重载XMLHttpRequest.prototype.open
函数以劫持页面上的Ajax调用。
我正在使用以下代码:
// ==UserScript==
// @name name
// @namespace namespace
// @description desc
// @include https://url*
// @version 1.0
// ==/UserScript==
if (XMLHttpRequest.prototype) {
//New Firefox Versions
XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;
var myOpen = function(method, url, async, user, password) {
//call original
this.realOpen (method, url, async, user, password);
myCode();
}
//ensure all XMLHttpRequests use our custom open method
XMLHttpRequest.prototype.open = myOpen ;
}
在开始使用GM API之前,此方法效果很好。 当我仅myOpen
添加到meta节时,我的代码中断了,不再调用myOpen
:
// @grant GM_getValue
真的可以是任何GM API,我的代码都会中断。 即使使用GM API,脚本中的其他所有内容也都可以正常工作,只是XMLHttpRequest.prototype.open
函数的重载被打破。
我可以通过使用waitForKeyElements
来解决该waitForKeyElements
,但是,我不喜欢它,因为它使用间隔会降低浏览器的速度。
有什么想法为什么GM API会打破XMLHttpRequest.prototype.open
调用的重载?
非常感谢,
彼得
@grant
指令重新打开Greasemonkey的沙箱-必须使用任何GM_
函数。
这样, prototype
覆盖将仅影响脚本范围,而您希望它影响页面范围。 为了解决这个问题,您需要注入替代。 像这样:
function overrideXhrFunctions () {
if (XMLHttpRequest.prototype) {
//New Firefox Versions
XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;
var myOpen = function(method, url, async, user, password) {
//call original
this.realOpen (method, url, async, user, password);
myCode();
}
//ensure all XMLHttpRequests use our custom open method
XMLHttpRequest.prototype.open = myOpen ;
}
}
addJS_Node (null, null, overrideXhrFunctions) {
//-- addJS_Node is a standard(ish) function
function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
var D = document;
var scriptNode = D.createElement ('script');
if (runOnLoad) {
scriptNode.addEventListener ("load", runOnLoad, false);
}
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
targ.appendChild (scriptNode);
}
请注意,混合使用GM_
函数和注入的代码可能会比较棘手。 请参阅“如何在注入的代码中使用GM_xmlhttpRequest?” 一种做到这一点的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.