Search code examples
javascriptvideostreamhook

Web how to hook media request and modify the media request response?


I've videos host on the CDN. But the video file has been modified. So the video cannot play directly.

In my app, I can reverse the modification of the video before play.

But how can I do it in the browser? There is ajax hook, and I've tryed it, it cannot hook the midia stream.


Solution

  • The video file header is encrypted by modify the header purposely.

    Firstly, if you are trying to encrypt video, this doesn't provide you much protection. I recommend using some sort of DRM with Encrypted Media Extensions. This will ensure your video cannot be accessed without some extra effort. Nothing is fool-proof, but this is at least a lot better.

    Web how to hook media request and modify the media request response?

    You can use a Service Worker to handle the request/response for anything, including media elements.

    Basically, a Service Worker serves as a proxy, intercepting the requests. If it chooses, it can handle the request itself. Normally this is used to do something special with caching, but you can use this same method to modify the response data as you see fit. At the very basic level, your service worker will do something like this:

    self.addEventListener('fetch', (event) => {
      event.respondWith(
        // Your modified data in a Response object here
      );
    });
    

    There's quite a bit you need to implement though to get started. You can find a full tutorial here:

    https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers

    Also note, be mindful of range headers in the requests. These are common with media data, and you'll need to handle them in your Service Worker scripts!