sindresorhus / electron-serve

Static file serving for Electron apps
MIT License
437 stars 34 forks source link

Add an option to intercept localhost instead of custom protocol #41

Open kirill-konshin opened 5 months ago

kirill-konshin commented 5 months ago

In some cases like this one a true http://localhost:xxx URL is needed, in this example in order to make YouTube IFRAME embed to work properly (in this example it's file: protocol, but it will break the same way with app: protocol.

I wrote a small hack to do so (for demo purposes, simplified):

import { protocol } from 'electron';
import fetch from 'node-fetch';

const localhostUrl = 'http://localhost:3000';

protocol.interceptBufferProtocol('http', (request, callback) => {
    if (request.url.includes(localhostUrl)) {
        let fileUrl = request.url.replace(localhostUrl, '');
        if (fileUrl === '/')  fileUrl = 'index.html';
        fs.readFile(path.join(indexPath, fileUrl))
            .then(callback)
            .catch(callback);
        return;
    }

    fetch(request.url, request)
        .then((res) => res.buffer())
        .then(callback)
        .catch(callback);
});

I wonder if it's possible to include something like this into the lib, I can send a pull request if it is OK.

P.S. The only drawback of this sample is necessity to fetch all external URLs, but so far it worked pretty OK for YouTube embed in my case.

There's also a way to redirect all requests to http://localhost into app://- but I haven't tried it yet: https://www.electronjs.org/docs/latest/api/web-request#webrequestonbeforerequestfilter-listener