Skip to content

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

@kirill-konshin

Description

@kirill-konshin

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions