Sunday, December 31, 2017

HTML5 Video - Get final src URL destination

Leave a Comment

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.

1 Answers

Answers 1

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 }); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment