问题
Ultimately what I am looking for is a way to actually block all network traffic on a given browser tab. So I don't know if blocking HTTP requests would block things like streaming videos and stuff, but it's a start.
The reason for this question is that I have moved to a developing country with expensive internet and I am annoyed at websites that continue to suck up bandwidth after the page has apparently finished loading. That includes pages with infinite scrolling (seems to be becoming popular on news sites), sites that automatically start playing videos, and any other kind of stuff that might be running in the background. I could not find a Chrome extension to turn off/on internet traffic for a tab. I know that it is possible to set a tab to offline under Developer Tools > Network, but it is not practical to use that method constantly for regular browsing. I want to be able to turn of network traffic with a hotkey or even automatically after a page has loaded.
I think the following code which I found elsewhere on SO works to intercept an HTTP request. But then I don't know how to block it at that point.
XMLHttpRequest.prototype.send = function() {
//what now?
}
And one more thing. After I have blocked all requests, how can I re-enable them? (How do I safely revert XMLHttpRequest.prototype.send
to it's original form?) I suppose I could try to capture the original function in a variable and "re-attach" it later, but for an object that would require cloning, and I can't use a library like jQuery. I just tried:
bob = Object.create(XMLHttpRequest.prototype.send)
XMLHttpRequest.prototype.send = function() {
console.log("Nope.")
return false
}
XMLHttpRequest.prototype.send = bob
But that didn't seem to work.
回答1:
You could simply add a return false
and this will block every .send()
methods.
Working fiddle (for code testing purpose) https://jsfiddle.net/L77cwcgb/
Actual snippet:
XMLHttpRequest.prototype.send = function() {
return false;
}
来源:https://stackoverflow.com/questions/44065856/is-there-a-way-to-block-http-requests-with-javascript