Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we use electron.protocol.interceptFileProtocol with only certain paths, leaving other requests untouched?

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?

like image 419
trusktr Avatar asked May 01 '19 22:05

trusktr


2 Answers

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.

like image 74
Adam Butler Avatar answered Oct 21 '22 06:10

Adam Butler


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');
})
like image 45
XavierP Avatar answered Oct 21 '22 07:10

XavierP