是否可以阻止特定站点(例如:facebook.com)发送特定的发布请求?
有什么方法可以“禁止”facebook 发布到特定 url?
我正在尝试阻止“https://www.messenger.com/ajax/mercury/delivery_receipts.php?dpr=2”请求
最佳答案
您可以在客户端阻止 AJAX 请求。
首先您需要覆盖XMLHttpRequest.prototype.open
。在此函数中,使用提供的参数调用原始 open
函数。然后存储对此XMLHttpRequest
的send
函数的引用。最后覆盖这个XMLHttpRequest
的send
函数。
在新的 send
函数中,比较提供给 open
函数调用的方法和 post 参数。如果它通过了比较,则使用原始参数调用原始的 send
函数。如果没有通过,什么都不做,你已经成功阻止了请求。
function blockXHR(compare) {
const open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
open.apply(this, arguments);
const send = this.send;
this.send = function() {
if(compare(method, url)) {
return send.apply(this, arguments);
}
console.log('blocked request');
};
};
}
下面演示中的其余代码用于演示此功能的使用,并且它确实有效。为简单起见,我使用了 ECMAScript 2015 语言规范中引入的一些功能,但这些功能都不是完成此任务所必需的。
function blockXHR(compare) {
const open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
open.apply(this, arguments);
const send = this.send;
this.send = function() {
if(compare(method, url)) {
return send.apply(this, arguments);
}
console.log('blocked request');
};
};
}
const requestFactory = (method, url, callback) => {
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', callback);
xhr.open(method, url);
xhr.send();
};
const comparisonFactory = (targetMethod, targetURL) =>
(method, url) => !(method === targetMethod && url === targetURL);
const callback = event => console.log(event.target.status);
blockXHR(comparisonFactory('POST', 'http://placehold.it/1x1'));
requestFactory('POST', 'http://placehold.it/1x1', callback); // blocked request
requestFactory('GET', 'http://placehold.it/1x1', callback); // 200
requestFactory('POST', 'http://placehold.it/1x1?hello', callback); // 200
关于javascript - 阻止网站发送特定的帖子请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911295/