Rophy Tsai
Rophy Tsai

Reputation: 51

How can I intercept requests against file and change them to http protocol?

In Electron, is it possible to intercept requests against file:/// and redirect them to http?

I have checked the Electron protocol page, but it's not obvious if this is supported or not.

Upvotes: 5

Views: 5409

Answers (2)

deepak
deepak

Reputation: 113

There is another way I was able to address this and interestingly the word "intercept" in the question has a lot to do with it :)

There is a function interceptHttpProtocol() on the protocol object you can use.

Sample code:

app.on("ready", () => {
    protocol.interceptHttpProtocol("http", function(request, callback) {
    var parsedUri = url.parse(request.url);

    var filePath = path.join(__dirname, parsedUri.pathname);
    request.url = "file://" + filePath; 

    callback(request);
  });

  var mainWindow = new BrowserWindow();

  mainWindow.loadURL("http://localhost/index.html");
});

Hope that helps

Upvotes: 1

Luke
Luke

Reputation: 2168

You could use protocol.registerHttpProtocol with the scheme file to intercept file: requests, and instead make an HTTP request.

Example (untested):

const {app, protocol} = require('electron')
const path = require('path')

app.on('ready', () => {
  protocol.registerHttpProtocol('file', (request, callback) => {
    const url = request.url.substr(8)
    callback({url: 'http://example.com/' + url)})
  }, (error) => {
    if (error) console.error('Failed to register protocol')
  })
})

Note: this sample may need refining as the file path may include the drive letter, which would be invalid for an HTTP request.

Upvotes: 2

Related Questions