I'd like to intercept certain HTTP requests and replace them with files. So I thought I could use electron.protocol.interceptFileProtocol
like so:
protocol.interceptFileProtocol('http', (request, callback) => {
// intercept only requests to "http://example.com"
if (request.url.startsWith("http://example.com")) {
callback("/path/to/file")
}
// otherwise, let the HTTP request behave like normal.
// But how?
})
How do we allow other http
requests other than http://example.com
to continue working as normal?
Not sure if there is a way to do this exactly? but I did something similar which is to use session.defaultSession.webRequest.onBeforeRequest
See: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest
something like
session.defaultSession.webRequest.onBeforeRequest({urls: ['http://example.com']}, function(details, callback) {
callback({
redirectURL: 'file://' + this.getUrl(details.url)
});
});
If you need more than a redirect you could redirect to your own custom protocol (eg. a url like mycustomprotocol://...
). You can implement your own protocol handler with protocol.registerStringProtocol
, etc.
I used both onBeforeRequest and registerStringProtocol separately in electron without issues so far but never both together - should work together though I geuss.
When using protocol.interceptXXXXProtocol(scheme, handler)
, we are intercepting scheme protocol and uses handler as the protocol’s new handler which sends a new XXXX request as a response, as said in the doc here.
However, doing so totally breaks the initial handler for this specific protocol, which we would need after handling the callback execution. Thus, we just need to restore it back to its initial state, so that it can continue working as normal :)
Let's use: protocol.uninterceptProptocol(scheme)
protocol.interceptFileProtocol('http', (request, callback) => {
// intercept only requests to "http://example.com"
if (request.url.startsWith("http://example.com")) {
callback("/path/to/file")
}
// otherwise, let the HTTP request behave like normal.
protocol.uninterceptProtocol('http');
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With