electron: [Bug]: video files not seekable with protocol.handle

Preflight Checklist

Electron Version

25.1.0

What operating system are you using?

Other Linux

Operating System Version

Linux Mint 21.1

What arch are you using?

x64

Last Known Working Electron version

No response

Expected Behavior

I’m using a custom protocol in place of file:// URLs for a video player. This works:

protocol.registerFileProtocol("video", (request, callback) => {
  callback(request.url.slice("video://".length))  // simplified path for this example
})

Since protocol.registerFileProtocol got deprecated in version 25, I tried the suggested alternative protocol.handle as per the update notes:

protocol.handle("video", (request) => {
  return net.fetch(request.url.replace(/^video:/, "file:"))  // simplified path
})

This allows me to play videos. However now when I set .currentTimeon a <video> element with a video://… source, it just jumps back to zero. video.seekable.end() is always 0. This breaks seeking in HTML5 videos with custom protocol URLs.

I’ve also tried this, with the same result:

protocol.handle("video", (request) => {
  return new Response(fs.readFileSync(request.url.replace(/^video:/, "file:")))
})

Not sure if it matters, the scheme is registered like this:

protocol.registerSchemesAsPrivileged([
  {
    scheme: "video",
    privileges: {
      secure: true,
      bypassCSP: true,
      stream: true,
    },
  },
])

Expected behavior: The documented alternative to protocol.registerFileProtocol should allow serving seekable video files.

Actual Behavior

See above.

Testcase Gist URL

No response

Additional Information

No response

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 16
  • Comments: 63 (3 by maintainers)

Commits related to this issue

Most upvoted comments

protocol.handle with createReadStream(filePath) + range headers: completely broke it, the video never loads

Be sure that the Content-Length and Content-Range headers in the response are correct. If I recall correctly, our implementation (available here under the AGPLv3), originally had an off-by-one error.

Here is my solution. It works fine.

protocol.handle('media', async (request) => {
  try {
    const url = request.url.replace(/^media:\/\//, '');
    const filePath = path.join(uploadsDir, decodeURIComponent(url));
    log.info('Serving file from media://', filePath);
    if (!fs.existsSync(filePath)) {
      log.error(`File not found: ${filePath}`);
      return new Response('File not found', { status: 404 });
    }
    const fileStat = fs.statSync(filePath);
    const range = request.headers.get('range');
    let start = 0, end = fileStat.size - 1;
    if (range) {
      const match = range.match(/bytes=(\d*)-(\d*)/);
      if (match) {
        start = match[1] ? parseInt(match[1], 10) : start;
        end = match[2] ? parseInt(match[2], 10) : end;
      }
    }
    const chunkSize = end - start + 1;
    log.info(`Serving range: ${start}-${end}/${fileStat.size}`);
    const stream = fs.createReadStream(filePath, { start, end });
    const mimeType = getMimeType(filePath);
    return new Response(stream, {
      status: range ? 206 : 200,
      headers: {
        'Content-Type': mimeType,
        'Content-Range': `bytes ${start}-${end}/${fileStat.size}`,
        'Accept-Ranges': 'bytes',
        'Content-Length': chunkSize,
      },
    });
  } catch (error) {
    log.error('Error handling media protocol:', error);
    return new Response('Internal Server Error', { status: 500 });
  }
});

function getMimeType(filePath) {
  const ext = path.extname(filePath).toLowerCase();
  switch (ext) {
    case '.wav':
      return 'audio/wav';
    case '.ogg':
      return 'audio/ogg';
    case '.mp3':
      return 'audio/mpeg';
    case '.mp4':
      return 'video/mp4';
    case '.jpg':
    case '.jpeg':
      return 'image/jpeg';
    case '.png':
      return 'image/png';
    case '.gif':
      return 'image/gif';
    default:
      return 'application/octet-stream';
  }
}

In older versions of Electron, it was possible to seek by specifying a local file path directly to an HTMLMediaElement.

I understand that protocol.registerSchemesAsPrivileged is for security improvement. If Electron wants to promote this feature, it would be good to have an official sample that is equivalent to the version where the local file path was specified directly.

Or, when request.headers is specified as an option for net.fetch, I would like it to generate a response that takes Range into account if there is one.

protocol.handle("https", async (request) => {
    const path = "G:/big_buck_bunny_trailer_480p_logo.webm";
    const stats = await stat(path);

    const headers = new Headers();
    headers.set("Accept-Ranges", "bytes");
    headers.set("Content-Type", "video/webm");

    let status = 200;
    const rangeText = request.headers.get("range");

    let stream;
    if (rangeText) {
        const ranges = parseRangeRequests(rangeText, stats.size);

        const [start, end] = ranges[0];
        console.log(rangeText, stats.size, start, end);
        headers.set("Content-Length", `${end - start + 1}`);
        headers.set("Content-Range", `bytes ${start}-${end}/${stats.size}`);
        status = 206;
        stream = createReadStream(path, { start, end });
    } else {
        headers.set("Content-Length", `${stats.size}`);
        stream = createReadStream(path);
    }

    return new Response(stream, {
        headers,
        status,
    });
});

function parseRangeRequests(text, size) {
    const token = text.split("=");
    if (token.length !== 2 || token[0] !== "bytes") {
        return [];
    }

    return token[1]
        .split(",")
        .map((v) => parseRange(v, size))
        .filter(([start, end]) => !isNaN(start) && !isNaN(end) && start <= end);
}

const NAN_ARRAY = [NaN, NaN];

function parseRange(text, size) {
    const token = text.split("-");
    if (token.length !== 2) {
        return NAN_ARRAY;
    }

    const startText = token[0].trim();
    const endText = token[1].trim();

    if (startText === "") {
        if (endText === "") {
            return NAN_ARRAY;
        } else {
            let start = size - Number(endText);
            if (start < 0) {
                start = 0;
            }

            return [start, size - 1];
        }
    } else {
        if (endText === "") {
            return [Number(startText), size - 1];
        } else {
            let end = Number(endText);
            if (end >= size) {
                end = size - 1;
            }

            return [Number(startText), end];
        }
    }
}

image

@jonmajorc are you able to SEEK the video?

So, before v34, this kind of wasn’t an issue, assuming registerFileProtocol had a different implementation behind the scenes than protocol.handle. Now with v34, that seems to have changed. So that workaround of still using registerFileProtocol doesn’t work anymore, so it’s actually irrelevant to still using it and we can rather try to solve it with protocol.handle.

Now we tried the solution from https://github.com/electron/electron/issues/38749#issuecomment-2585189055 but we don’t really get any difference. Basically, we want to let videos autoplay and loop while Electron is serving the file via a protocol handler. We currently don’t see how we make this possible in Electron v34+. At least, on specific Linux based systems that doesn’t work. On a macOS build of the application, using the cache-control header to disabale the cache too for the video stream, seems to kind of work. But only for macOS so far.

Might somebody be able to provide a fully tested solution that works for them, including any workarounds with converting streams?

In testing further, I’ve found that my example does work on v36.7.2, but it does not work on v37.0.0.

I’ve also confirmed it does not work on v38.0.0-alpha.7 or v39.0.0-nightly.20250718 .

I’ve narrowed this further to v37.0.0-nightly.20250422 working and v37.0.0-nightly.20250423 not working, so I believe this issue started in one of these two commits

dd03cceda0384f62540b0cea650e73b091eab34b (more likely this one as it bumps Chromium) 686ae476963ed138135bc5f2934addcd1cc1e4ac

I’m struggling to figure out how I could bisect Electron and/or Chromium to further narrow this. What I’d like to be able to do is compile electron at commit dd03cceda0384f62540b0cea650e73b091eab34b and see if it works, and if it doesn’t, start stepping through the Chromium commits between when there were previously bumped and this commit. I’ve compiled Electron at it’s latest commit but haven’t gotten past that yet.

Edit: Someone else actually already found these commits here https://github.com/electron/electron/issues/47661 and there’s an open PR to fix it here https://github.com/electron/electron/pull/47703

@blurymind Here’s my minimal project https://github.com/agsimmons/electron-video-playback-example

Clone the repo, cd into it, run npm install, then npm run dev. It plays back the example_video.mp4 video in the root of the project.

Sorry, but this idea has been proposed before. It works well with electron 35, but not with electron 36 or electron 37.

how were you able to force a Response to accept a raw createReadStream?

It might be necessary to convert the fs read stream to a web-compatible stream (see the implementation linked in https://github.com/electron/electron/issues/38749#issuecomment-2313762452).

@cxw2299 When serving large files like videos or audio, browsers or media players often request partial data segments for:

  • Streaming content directly.
  • Seeking to specific positions within the file.

This code handles the Range header from the client to send only the required portion of the file.

what is confusing to me – why would registerFileProtocol work for streaming large files? Shouldn’t we be using registerStreamProtocol? Also, @personalizedrefrigerator has so much custom code, e.g. request with Range header handling. Does registerFileProtocol internally also handle requests with Range headers? If that’s the case, could that be in an utility mehtod so that we could use in protocol.handle?

Hello! I have the same problem on Windows. Video files prepared using protocol.handle cannot be seeked.

Electron: 25.1.0 OS: Windows 11 Pro x64 10.0.22621 Build 22621

Fiddle: https://gist.github.com/takumus/7b6d73df884df009f36bc6ff1979d5ff

This text was translated by Deepl.

Thank you for investigating 😃 Great findings. I’m hoping hard that the proposed fix (in the PR you linked to) will be merged asap to address the regression, otherwise we’ll have to rollback our app to Electron v36 (or modify our architecture to serve audio/video media resources via a local HTTP server, which comes with significant tradeoffs in our case).

@blurymind Here’s my minimal project https://github.com/agsimmons/electron-video-playback-example

Clone the repo, cd into it, run npm install, then npm run dev. It plays back the example_video.mp4 video in the root of the project.

I was finally able to get this working with protocol.handle . Autoplay, seeking, and looping are all working for me on both Linux and Windows.

  • The protocol needs the standard privilege; I was having issues without it
  • I did not see a difference in behavior with or without the stream privilege, but the docs seem to suggest to use it
  • Your handler code needs to properly handle range requests
    • Look for the Range header, and return the correct range of the file from disk
    • Return the correct Content-Length header for the given range
    • Return Accept-Ranges: bytes to state that the handler understands range requests
    • Return Content-Range header to say which range was returned and the full file size
  • Use createReadStream from node:fs to open a stream for the file on disk. If providing a range of the file, use the start and end options. Include this stream object as the response body. Typescript complains about this not being a compatible type, but it appears to work properly. I’d appreciate any insight into this.

I can’t share my code directly, but I hope this is helpful

@blurymind on my front its just

<video src="video://..." preload="auto" />

Ok none of these examples here make it seekable for me. I was thinking its because its not piping the stream like theexpress example (which btw works) https://github.com/bootstrapping-microservices/video-streaming-example/blob/master/index.js I tried to do fs.createReadStream(path).pipe(res); but the response from the example which nodejs uses is not compatible with that code at all and couldnt find any clear example of how to pipe the video stream with node

And man I’ve been trying literally every one of these examples and from other bug reports too. AI was also not successful.

You should try the solution I’ve given.

It works on Window with electron 36 and even with the latest 37.1.

You are loading the entire file to a Blob, which might bloat the memory, not recommended for large files

Brothers!i find the loadURL on electron must take a long time to show a win,have someting to deal this?

// I needed all these marked as `true`
protocol.registerSchemesAsPrivileged([
  {
    scheme: 'app',
    privileges: {
      secure: true,
      supportFetchAPI: true,
      bypassCSP: true,
      stream: true,
      standard: true,
    },
  },
]);

// ...

protocol.handle('app', async request => {
  const url = request.url.replace(/^app:\/\//, '/'); // Replacing the app:// with a / because I want find the file from the root of file system.
  return net.fetch(pathToFileURL(url).toString());
});

in the renderer

<video src="app://path/to/video.mp4" controls />

So, before v34, this kind of wasn’t an issue, assuming registerFileProtocol had a different implementation behind the scenes than protocol.handle. Now with v34, that seems to have changed. So that workaround of still using registerFileProtocol doesn’t work anymore, so it’s actually irrelevant to still using it and we can rather try to solve it with protocol.handle.

Now we tried the solution from #38749 (comment) but we don’t really get any difference. Basically, we want to let videos autoplay and loop while Electron is serving the file via a protocol handler. We currently don’t see how we make this possible in Electron v34+. At least, on specific Linux based systems that doesn’t work. On a macOS build of the application, using the cache-control header to disabale the cache too for the video stream, seems to kind of work. But only for macOS so far.

Might somebody be able to provide a fully tested solution that works for them, including any workarounds with converting streams?

@renestalder I have the exact same behavior. Intermittent playing on Mac & registerFileProtocol doesn’t work either. Difficult to debug for sure. Hoping to get some time Sunday or early next week to give it another go. Frustrating.

Will post here if I get it figured out before someone else.

how were you able to force a Response to accept a raw createReadStream?

It might be necessary to convert the fs read stream to a web-compatible stream (see the implementation linked in #38749 (comment)).

Thanks, that is what I have now and still having issues. Something along the lines of that nodeStreamToWeb is still required as the node double controller close interaction still exists, for those following along.

Struggling to get this work in Electron v34.2.0.
<video /> elements load the src intermittently, but then cannot be played. For some reason, toggling on ‘autoPlay’ seems to make it more likely that the video will load.

@dev-techfago how were you able to force a Response to accept a raw createReadStream?

agree with @6zz seem like a bug in electron, maybe there is a way to fallback to some Electron.ProtocolResponse kinda like registerFileProtocol does.

+1, I’m also switching back to registerFileProtocol

Things I tried:

  • protocol.handle with net.fetch: Loading a 2GB local video takes 10+ seconds
  • protocol.handle with createReadStream(filePath): same result
  • protocol.handle with createReadStream(filePath) + range headers: completely broke it, the video never loads

These were all with stream: true in the scheme privileges. I wonder if this is related to #41032 or #40447.

On the other hand registerFileProtocol loads instantly, matching the same performance as using an <input type="file"> with createObjectURL(). Even the largest videos come through at disk read speed.

Any update on this? Seems to have affected a lot of video & music players built on electron. Have been using the depreciated handlers but as @vincaslt said it triggers a false-positive virus warning in windows.

The old handler is now also throwing these errors: [50325:0701/153404.655428:ERROR:ffmpeg_common.cc(959)] Unsupported pixel format: -1

This still seems to be an issue with Electron 31.0.0.

Still an issue. Also, similar as to this comment from 2021t, the issue only affects the first load of a video item. I.e. if we close and re-open the video, then suddenly seeking does work.

Affects plain audio files, as well. Present on Mac and Windows (haven’t tested Linux yet, but if someone wants, just ask)

Workaround is staying on the deprecated API for the time being.

@philer the fiddle by @takumus is what i was looking for! i can try to look into this more but @nornagon (who is off work at the moment - back midsummer) may be a better person to investigate depending on how far i get.