Reputation: 51
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
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
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