Skip to content

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

Open

Description

@philer

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

Activity

  1. changed the title [-][Bug]: [/-] [+][Bug]: video files not seekable with protocol.handle [/+] on Jun 13, 2023
  2. added
    blocked/need-repro
    on Jun 13, 2023
  3. github-actions commented on Jun 13, 2023

    @github-actions
    Contributor

    Hello @philer. Thanks for reporting this and helping to make Electron better!

    Would it be possible for you to make a standalone testcase with only the code necessary to reproduce the issue? For example, Electron Fiddle is a great tool for making small test cases and makes it easy to publish your test case to a gist that Electron maintainers can use.

    Stand-alone test cases make fixing issues go more smoothly: it ensure everyone's looking at the same issue, it removes all unnecessary variables from the equation, and it can also provide the basis for automated regression tests.

    Now adding the blocked/need-repro label for this reason. After you make a test case, please link to it in a followup comment. This issue will be closed in 10 days if the above is not addressed.

  4. philer commented on Jun 13, 2023

    @philer
    Author

    @codebytere I don't think this is something I can reproduce in a fiddle…

  5. removed
    blocked/need-repro
    on Jun 13, 2023
  6. moved this to Unsorted Items in 25-x-yon Jun 14, 2023
  7. takumus commented on Jun 14, 2023

    @takumus

    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.

  8. added
    status/confirmed
    has-repro-gist
    and removed on Jun 14, 2023
  9. 65 remaining items

  10. blurymind commented on Aug 4, 2025

    @blurymind

    This pr resolves this problem? #47703

  11. zoy-l commented on Aug 9, 2025

    @zoy-l
    Contributor

    Hey guys, here’s my solution. It works on version 37.2.6. macOS/Windows work

    export const FileProtocolName = 'myfile'
    
    export const FileProtocol = isWin() ? `${FileProtocolName}:///` : `${FileProtocolName}:/`
    // You can manually select which attributes to turn on.
     protocol.registerSchemesAsPrivileged([
        {
          scheme: FileProtocolName,
          privileges: {
            standard: true,
            secure: true,
            bypassCSP: true,
            allowServiceWorkers: true,
            supportFetchAPI: true,
            stream: true,
            corsEnabled: true
          }
        }
      ])
    
    export function registerFileProtocol(session: Electron.Session) {
      session.protocol.handle(FileProtocolName, (request) => {
        try {
          const url = request.url.slice(FileProtocol.length)
          const filePath = path.normalize(decodeURIComponent(url))
    
          // const allowedBasePath = app.getAppPath();
          // if (!filePath.startsWith(allowedBasePath)) {
          //   console.error('Security Violation: Forbidden path access attempt:', filePath);
          //   return new Response('Forbidden', { status: 403 });
          // }
    
          if (!fs.existsSync(filePath)) {
            return new Response('File not found', { status: 404 })
          }
    
          const mimeType = mime.lookup(filePath) || 'application/octet-stream'
    
          const stat = fs.statSync(filePath)
          const fileSize = stat.size
          const range = request.headers.get('range')
    
          const headers: Record<string, string> = {
            'Content-Type': mimeType,
            'Accept-Ranges': 'bytes'
          }
    
          if (range) {
            const parts = range.replace(/bytes=/, '').split('-')
            const start = parseInt(parts[0], 10)
            const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1
    
            if (start >= fileSize || end >= fileSize) {
              return new Response(null, { status: 416, headers })
            }
    
            const chunksize = end - start + 1
    
            const stream = fs.createReadStream(filePath, { start, end })
    
            headers['Content-Range'] = `bytes ${start}-${end}/${fileSize}`
            headers['Content-Length'] = chunksize.toString()
    
            return new Response(stream as Placeholder, {
              status: 206,
              headers
            })
          } else {
            const stream = fs.createReadStream(filePath)
            headers['Content-Length'] = fileSize.toString()
    
            return new Response(stream as Placeholder, {
              status: 200,
              headers
            })
          }
        } catch (error) {
          return new Response('Internal Server Error: ' + (error as Error).message, { status: 500 })
        }
      })
    }
  12. danielweck commented on Aug 11, 2025

    @danielweck

    This pr resolves this problem? #47703

    Yes, we shipped with v37 since this fix (before, we stayed on v36)

  13. cxw2299 commented on Jun 18, 2026

    @cxw2299

    if my video without autoplay , After some time, an error occurred: "The operation was aborted."

  14. added theissue type on Jul 28, 2026
  15. akabekobeko commented on Oct 3, 2026

    @akabekobeko

    Follow-up to my earlier comments (#38749 (comment)): I found what made currentTime fail outside the buffered range, and it is not a bug in protocol.handle or in the Range handling of the handler.

    Symptom

    Audio served over a custom scheme (protocol.handle, stream: true, correct 206 / Content-Range / Accept-Ranges responses) plays fine, but setting currentTime to a position outside buffered stops playback with:

    MediaError code=2 PipelineStatus::PIPELINE_ERROR_READ: FFmpegDemuxer: data source error
    

    Cause

    Chromium's media stack validates that every Range response for a resource comes from the same origin as the first one (UrlData::ValidateDataOrigin in third_party/blink/renderer/platform/media/url_index.cc). The check only runs when the element is loaded in no-cors mode (cors_mode_ == CORS_UNSPECIFIED, i.e. no crossOrigin attribute):

    bool UrlData::ValidateDataOrigin(const KURL& origin) {
      if (!data_origin_) {
        data_origin_ = origin;
        return true;
      }
    
      if (cors_mode_ == UrlData::CORS_UNSPECIFIED) {
        // If both origins are null return true, otherwise
        // SecurityOrigin::AreSameOrigin will create a unique nonce for each.
        if (data_origin_->IsNull() && origin.IsNull()) {
          return true;
        }
        return SecurityOrigin::AreSameOrigin(data_origin_.value(), origin);
      }
      ...

    A custom scheme that is not registered with standard: true has no host-based origin. Each comparison creates a fresh opaque origin, so the first response passes (nothing to compare yet) and the very first follow-up Range request, which a seek outside buffered triggers, fails the check. The data source is marked failed and the demuxer reports PIPELINE_ERROR_READ.

    This also explains the observations in this thread and in #51442 that adding standard: true made seeking work: a standard scheme yields a stable tuple origin, so the comparison succeeds.

    Verified on Electron 44.4.5 (macOS, Apple Silicon)

    Same app, same protocol handler, same files (1 h m4a and CBR mp3); the only difference is how the element is loaded:

    <audio> load mode seek outside buffered
    no crossOrigin (opaque response) fails with PIPELINE_ERROR_READ
    crossOrigin = "anonymous" + Access-Control-Allow-Origin: * on every response + corsEnabled: true on the scheme works, Chromium issues Range: bytes=N- and playback continues

    Full write-up and the fix are in akabekobeko/parade#269 (the PR description is in Japanese; the summary above covers the same findings in English).

    Workarounds

    Either of these is enough:

    1. Register the scheme with standard: true so it has a real origin.
    2. Keep the scheme non-standard but load the element in CORS mode: set crossOrigin = "anonymous" on the <audio> / <video>, add corsEnabled: true to the scheme privileges, and return Access-Control-Allow-Origin on every response (including the 206 ones). This is also what you need anyway if the element feeds a MediaElementAudioSourceNode, which outputs silence for tainted sources.

    The handler itself still has to honor Range and answer with 206, Content-Range and Content-Length, as others noted above. Chromium always sends Range: bytes=0- on the first media request, so a handler that only looks at the no-Range path never sees the media element's requests.

    It might be worth a note in the protocol docs: for <audio> / <video> over a custom scheme, use standard: true or CORS mode, otherwise seeking fails once the element needs a byte range that is not buffered yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    25-x-ybug 🪲component/protocolhas-repro-gistplatform/allstatus/confirmed

    Type

    Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions