简体   繁体   中英

HTML5 Video - Get final src URL destination

I'm displaying video content from a 3rd party service on my website:

<video src="http://www.example.com/api/v1/media/video.mp4?status=true"></video>

The service detects the user's geo-location and browser's language and returns video that fit those parameters.

http://www.example.com/api/v1/media/video.mp4?status=true REDIRECT TO http://www.example.com/api/v1/media/US/EN/English_CAT.mp4

Other than the media URL, the service doesn't provide the actual file name that particular user received.

How can I fetch the final media path/name? Tried multiple ways but iframes blocked by X-Frame-Options: DENY and AJAX blocked as well.

The short answer is you probably can't do this all on the client-side. You will run into same-origin issues. In addition, it is not possible to directly get the HTTP headers of a <video> element.

If the service provider for the videos enables CORS support you may be able to get the final URL via a workaround. Even with CORS enabled you won't be able to get the HTTP headers or final URL of the video from the <video> element.

You can work around this by:

  1. Make a 2nd HTTP request ( XMLHttpRequest , fetch , $.ajax , etc) to the same URL.
  2. Make a HEAD request instead of a GET request. GET requests will attempt to retrieve the entire file. HEAD requests do not download the body, only the headers, which would be enough for resolving the redirect.
  3. Look in the headers of the HEAD response for the final URL path.

Here is an example that uses fetch :

var request = new Request(yourVideoUrl);
request.mode = 'cors';
request.method = 'HEAD';

fetch(request)
.then(function(res){
  console.log(res.url); // This should be the final URL
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM