Youtube Blob urls don't work in browsers but in src - javascript

I know that there are no blob urls only objects.
I made my own blob object for a video buffer and then I used it in a src of video tag which is something like blob://website.com/blablobbla . I opened this url in the browser it worked
when I opened the url of youtube video src (blob url) into a new tab it did't work but mine video src (blob url) worked
I want to know how can I do the same with my blob urls so that they only work in the src of the html video tag and give error or don't work in the external tab/window of the browsers.I just want to know the technology behind this and blob objects and their url properties.

The question seems somewhat vague to me, so here is what I interpret (also from the code in the fiddle-images in your question):
you receive a Blob (image's binary data) through a XMLHttpRequest() GET-request (responseType = 'blob')
you create a Blob URL with URL.createObjectURL() in the URL Store for XMLHttpRequest() response-object (the Blob holding the binary data)
you set the resulting Blob URL-string as src for a image (and append the image to the document, thereby showing the image you just downloaded)
You "don't want it to work in new tab" ("it" being the Blob URL-string I assume).
In your comments you say:
In fiddle I inspected the image and copied the src and then pasted it in new tab and it worked and showed the image I don't want the image to be shown directly with the blob url.
If you go to youtube and open the src of video in new tab : It will not work,, I want this to happen
It appears to me that you do not want the user to be able to view/download the blob when they copy the Blob URL-string (by examining the live source or simply right-click-on-image>>Copy Imagelocation) and paste it into a new tab/window (for which you give youtube as an example).
But you are also talking about video's.
TL;DR: It seems your question/bounty might be mixing up 2 different types of URL returned by window.URL.createObjectURL();:
Blob URL referencing (objects that represent) 'raw local data' (like (Local-)File, Blob, etc.)
For these you want to automatically (or programmatically) revoke the Blob URL from the browser's URL Store (which you could consider a simplified local webserver inside the browser, only available to that browser).
var myBlobURL=window.URL.createObjectURL(object, flag_oneTimeOnly);
returns a re-usable Blob URL which can be revoked with: window.URL.revokeObjectURL(myBlobURL) (adds the Blob URL string to the Revocation List).
Note: there used to be a second argument flag_oneTimeOnly which used to revoke the Blob URL automatically after it's first use, but that is currently no longer part of the spec! Also this flag often didn't work anyway (at least in firefox).
var myBlobURL=window.URL.createFor(object);
returns a Blob URL that is automatically revoked after it's first use.
Note: quite some browsers were 'late' to implement this one.
MediaSource object URL referencing a special MediaSource Object
These URL's are
only intended to link src of a HTMLMediaElement (think <audo> & <video> elements) to the special MediaSource Object
Note: a new tab/window is not an HTMLMediaElement
already automatically revoked
Note: even though they are created through window.URL.createObjectURL();
Here's what's happening for the fiddle in your question's image and similar code that downloaded a video as Blob (where you downloaded the whole video-file's data/binary on the server using an xhr) or any other 'local' data:
You are essentially using the 'bare' 'un-enhanced' File-API.
The URL Store is only maintained during a session (so it will survive a page-refresh, since it is still the same session) and lost when the document is unloaded.
So, if your fiddle is still open, then fiddle-document (the document that created the Blob URL) is obviously not yet unloaded, and therefore it's Blob URLs are available to the browser (any tab/window) as long as it is not revoked!
This is a relevant feature: you can build/download/modify a Blob in the browser, create a Blob URL and set it as href to a file-download link (which the user can right-click and open in a new tab/window!!)
Close the fiddle or revoke the Blob URL from the URL Store and the Blob URL is no longer accessible (also not in a different tab/window).
Try yourself with your modified fiddle: https://jsfiddle.net/7cyoozwv/
In this fiddle it should now no longer be possible to load your sample image into a different tab/window after you copied the image url (once the image is displayed in your page).
Here I revoked the URL manually (revokeObjectURL()) as it is currently the best cross-browser method (partially due to the api not yet fully being stabilized).
Also note: an element's onload event can be an elegant place to revoke your Blob URL.
Here is what's happening to an <audio> or <video> source linked to an MediaSource Object using an MediaSource object URL returned by window.URL.createObjectURL(MediaSource):
The Media Source Extensions (MSE) also extend the File-API's window.URL.createObjectURL() to accept a MediaSource Object. The (current draft of the) URL Object Extension specifies that:
This algorithm is intended to mirror the behavior of the createObjectURL()[FILE-API] method with autoRevoke set to true.
Note that the current spec of the File API's window.URL.createObjectURL() no longer has an autoRevoke (or flag_oneTimeOnly) boolean flag accessible to the programmer who should be using window.URL.createFor() for this purpose instead. I wonder when the Media-Source spec will mimic that (and for backward compatibility alias their createObjectURL() to a new createFor() extension (seems more appropriate as that is how it seems to be intended to work currently)).
These resulting automatically revoked URL-strings are only intended to link the src of a HTMLMediaElement (think <audo> & <video> elements) to the special MediaSource Object.
I don't think that an empty Document (from a new tab/window) is a <audo> or <video> element.
Perhaps "A quick tutorial on MSE"(source: MSDN) might help clarify the difference and basic use:
To use the MSE API, follow these steps:
Define an HTML5 video element in the HTML section of a page.
Create a MediaSource object in JavaScript.
Create a virtual URL using createObjectURL with the MediaSource object as the source.
Assign the virtual URL to the video element's src property.
Create a SourceBuffer using addSourceBuffer, with the mime type of the video you're adding.
Get the video initialization segment from the media file online and add it to the SourceBuffer with appendBuffer.
Get the segments of video data from the media file, append them to the SourceBuffer with appendBuffer.
Call the play method on the video element.
Repeat step 7 until done.
Clean up.
You (or a big-time player like youtube who will dynamically select supported technologies for playback on the client's platform (so there is no way to tell for sure what kind of youtube video URL's you are talking about)) could be using the new special MediaSource Object to play video's (or audio).
This adds buffer-based source options to HTML5 video for streaming support (compared to to downloading a complete video file before playing or use an add-on like Silverlight or Adobe Flash to stream media).
Hope this is what you were after!

Actually, the URL that you're referring is just a "string" reference to the BLOB itself (which is created using the function window.URL.createObjectURL); So, that you can use it like a normal URL. And, the scope is also only until the document is unloaded.
So, I don't think it is possible for you to open the URL just using browser. And also I tried to re-create what you're saying but with no avail (in my own website, create a blob and put the URL into browser).
Below is the code
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://kurrik.github.io/hackathons/static/img/sample-128.png");
xhr.responseType = "blob";
xhr.onload = function response(e) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
console.log(imageUrl);
var imgDOM = document.createElement("img");
imgDOM.src = imageUrl;
document.getElementById("divImage").appendChild(imgDOM);
};
xhr.send();
The fiddle here
Update :
Ok, after I looked at it. seems like youtube is using media-source to stream the video.
I haven't updated the fiddle (cannot found a video that I can use). But, basically, It still using the same function (createObjectURL) to create the blob URL. But, instead of using the source (image, video, etc) to pass to the function. You should pass the MediaSource object into the function.
And then, you use the blob URL and pass it into the video.src. Therefore, when you try to open the blob link. You should not be able to see the video again.

Related

Load m3u8 video file as Blob with different orign

I'm attempting to stream video using a Blob URL created from an m3u8 URL.
The m3u8 file contains only relative paths.
E.g.
file1.ts
file2.ts
...
The m3u8 file is stored on a separate host (e.g. the URL is fileserver.com/path/thevideo.m3u8) than the website loading the video (e.g. the URL is website.com).
Therefore, after converting the m3u8 URL to a Blob, the video player subsequently looks for:
website.com/file1.ts
website.com/file2.ts
Whereas, the actual URLs are:
fileserver.com/path/file1.ts
fileserver.com/path/file2.ts
Question is, is there any way to get the video player (I'm using VideoJS) to use the correct URL prefix?
The code I used for Blob URL generation is here: set video objects source file to a blob url
I can confirm that it works if the m3u8 file contains the full *.ts URLs instead of the relative paths, but I want to see if this is possible using only the relative path as that would be more convenient.
You can attach a custom handler for requests made by videojs/http-streaming engine.
player.tech().vhs.xhr.beforeRequest = function(options) {
options.uri = options.uri.replace('example.com', 'foo.com');
return options;
};
Note: You should make a check with safari hls playback if you're using overrideNative option.

createObjectURL overload resolution failed

I am trying to load a PDF as a blob in JavaScript from the backend, but receive Failed to execute 'createObjectURL' on 'URL': Overload resolution failed. I'm not really sure where to go from here. I've looked at some of the other posts but none seem to deal with PDF, only audio.
The docs for createObjectURL say: "The new object URL represents the specified File object or Blob object", so I'm not sure what I'm doing wrong. (https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL)
From my backend, I set: Content-type: application/octet-stream then expect to be able to set the iFrame source, but it's not working.
I can verify that the blob data is in fact being returned from the backend.
This is the JS code that uses the blob.
iframe.src = URL.createObjectURL(data);
EDIT 1:
I'm being asked to edit my question with why the suggested prior post doesn't solve my issue. Here's a copy/paste from my comments below:
I did see that post already and the accepted answer says: "Consider avoiding createObjectURL() method, while browsers are disabling support for it. Just attach MediaStream object directly to the srcObject property of HTMLMediaElement e.g. element." I'm not an expert with JavaScript but I don't think MediaStream will work.
EDIT 2:
Thanks to David Caldwell, in his comment he mentioned "src/srcObject"which made me look a little closer at the docs for MediaStream. I have something now that isn't erroring out. All I need is the correct Mime for the blob so I can use it in the iFrame src.
Here is what I have now that returns the srcObject:
var binaryData = [];
binaryData.push(data); //My blob
var foo = URL.createObjectURL(new Blob(binaryData, {type: "application/text"}));
console.log(foo); //gives me the correct object
Should I be using a Mime of "text"? I need to assign that object to the iFrame src.
EDIT3:
Using a MIME of text/plain, I get the following in the DOM:
<iframe id="iframe-target" src="blob:http://192.168.112.12/e25a4404-8233-44f0-86b3-1fff1109805f" width="100%" height="100%">
#Document
<html>
<head></head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">[object Object]</pre> <--'object Object' is the issue
</body>
</html>
</iframe>
I now see the blob object in the iframe but the HTML within the iframe is showing as an Object. The object is actually a PDF but as it is, I can't view it. I still think this is a MIME issue, but I'm not sure what to use.
I think you can still use Content-type: application/pdf on the response, the point is to receive a valid blob.
When creating the object URL, assuming data is still your blob, you should do:
var blobObj = new Blob([atob(data)], { type: "application/pdf" });
var url = window.URL.createObjectURL(blobObj);
document.getElementById("iframe-target").setAttribute("src", url);
Here, a few things are happening:
data is converted back to binary with atob()
this binary data is then passed as a byte array to the Blob() constructor
the Blob object is used with the MIME type to create the object URL
the resulting object URL can be used as the src attribute for an iframe
I've created a snippet as a small demo, here you can choose a local PDF file, which will be converted to base64, then used as the src attribute in an iframe. See the source code on CodeSandbox and see the demo of the sandbox here.
UPDATE: Removed embedded snippet.
As #K J pointed out in the comments, running the snippet embedded or from the CodeSandbox editor will produce errors.
At first glance, it appears that the browser blocks the resulting blob URL. This is because window.URL.createObjectURL prepends the blob URL differently based on the origin.
This isn't a problem in production, but makes demoing the solution a bit more difficult. Luckily, CodeSandbox deploys the app to a host, where the blob URL scheme and host will match the app URL:
In this case, the PDF will be shown as expected. I've tested the deployed version of the sandbox on Chrome, Safari, and Firefox.

IE frees blob urls

I have two audio files which have to be played one after the other.
In order to do this, I downloaded the two files using XHR
var xhr = new XMLHttpRequest();
xhr.open('GET', fileURL, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
data = new Uint8Array(xhr.response);
//... other handling code
};
and constructed a Blob from them
var blob = new Blob([data], {type: 'video/mp4'})
These I used to construct Blob URLs
var url = URL.createObjectURL(blob)
which are then injected into <audio> tags. (audioDOM.src = url;)
This procedure works in Chrome and Firefox. However IE11 sometimes gives me a problem, it displays following notice:
One or more blob URLs were revoked by closing the blob for which they
were created. These URLs will no longer resolve as the data backing
the URL has been freed.
However, the weirdest part is that it does work (in IE) for the first file, but not for the second one. They both use the same code for the entire procedure, which is simply called using a different fileURL. Both files exist, are downloaded properly and have been logged to console for verification.
I attempted copying the data before constructing the blobs, but it does not seem to matter: the error remains.
Does anyone have an idea what causes the problem and how it could be fixed?
EDIT after sbgoran:
The entire script runs on a single document, which is not being reloaded. I am still confused why it is the case. I did manage to create a workaround by looping and creating a new URL when the audio fails to load, but this is not a workable solution. The weird part is that the method described above fails at random: sometimes the URL is available when loaded into the <audio> tag, sometimes it isn't.
Apart from sbgoran's answer, I have another possible cause - as discussed on WhatWG mailing list, there's a bug in IE that causes a Blob to be garbage collected when the variable that points to it goes out of scope - even when there are still object URLs pointing to the Blob that haven't been revoked.
A workaround could rely on holding on to the original Blob object in a variable as long as the object URL is needed, then nullifying the variable and revoking its object URL afterwards.
Based on Remarks section of MSDN createObjectURL method page it could be plenty of things that IE might complain about. I'm not sure if you read this MSDN page before but maybe it can help in some way.
I would especially check note about blob urls origin policy
Blob urls are subject to an origin policy. This means that they can only be used in documents that have the same site-of-origin as the document running the script that created the url. If you need to use the blob object from an that is running in a different domain, you must use the postMessage API to send the blob data to the frame and then create the blob: url there.
and
URL returned by createObjectURL is valid for the lifetime of the creating document,
which are then injected into <audio> tags.
Can you please give this code ?
Maybe IE has some kind of garbage collector, which frees the blob url as soon as there is no DOMString instance containing the blob url.
With this theory, creating your audio tag with innerHTML (and maybe setAttribute ?), I mean by concatenation of the url (foo.innerHTML = '<audio src="' + url + '" />';) implies that the only DOMString containing the blob url (the one returned by URL.createObjectURL) will be garbage collected some time after the end of your function.

Convert blob URL to normal URL

My page generates a URL like this: "blob:http%3A//localhost%3A8383/568233a1-8b13-48b3-84d5-cca045ae384f" How can I convert it to a normal address?
I'm using it as an <img>'s src attribute.
A URL that was created from a JavaScript Blob can not be converted to a "normal" URL.
A blob: URL does not refer to data the exists on the server, it refers to data that your browser currently has in memory, for the current page. It will not be available on other pages, it will not be available in other browsers, and it will not be available from other computers.
Therefore it does not make sense, in general, to convert a Blob URL to a "normal" URL. If you wanted an ordinary URL, you would have to send the data from the browser to a server and have the server make it available like an ordinary file.
It is possible convert a blob: URL into a data: URL, at least in Chrome. You can use an AJAX request to "fetch" the data from the blob: URL (even though it's really just pulling it out of your browser's memory, not making an HTTP request).
Here's an example:
var blob = new Blob(["Hello, world!"], { type: 'text/plain' });
var blobUrl = URL.createObjectURL(blob);
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.onload = function() {
var blobAsDataUrl = reader.result;
window.location = blobAsDataUrl;
};
reader.readAsDataURL(recoveredBlob);
};
xhr.open('GET', blobUrl);
xhr.send();
data: URLs are probably not what you mean by "normal" and can be problematically large. However they do work like normal URLs in that they can be shared; they're not specific to the current browser or session.
another way to create a data url from blob url may be using canvas.
var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)
as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)
For those who came here looking for a way to download a blob url video / audio, this answer worked for me. In short, you would need to find an *.m3u8 file on the desired web page through Chrome -> Network tab and paste it into a VLC player.
Another guide shows you how to save a stream with the VLC Player.
UPDATE:
An alternative way of downloading the videos from a blob url is by using the mass downloader and joining the files together.
Download Videos Part
Open network tab in chrome dev tools
Reload the webpage
Filter .m3u8 files
Look through all filtered files and find the playlist of the '.ts' files. It should look something like this:
You need to extract those links somehow. Either download and edit the file manually OR use any other method you like. As you can see, those links are very similar, the only thing that differs is the serial number of the video: 's-0-v1-a1.ts', 's-1-v1-a1.ts' etc.
https://some-website.net/del/8cf.m3u8/s-0-v1-a1.ts
https://some-website.net/del/8cf.m3u8/s-1-v1-a1.ts
https://some-website.net/del/8cf.m3u8/s-2-v1-a1.ts
and so on up to the last link in the .m3u8 playlist file. These .ts files are actually your video. You need to download all of them.
For bulk downloading I prefer using the Simple Mass Downloader extension for Chrome (https://chrome.google.com/webstore/detail/simple-mass-downloader/abdkkegmcbiomijcbdaodaflgehfffed)
If you opt in for the Simple Mass Downloader, you need to:
a. Select a Pattern URL
b. Enter your link in the address field with only one modification: that part of the link that is changing for each next video needs to be replaced with the pattern in square brackets [0:400] where 0 is the first file name and 400 is the last one. So your link should look something like this https://some-website.net/del/8cf.m3u8/s-[0:400]-v1-a1.ts.
Afterwards hit the Import button to add these links into the Download List of Mass Downloader.
c. The next action may ask you for the destination folder for EACH video you download. So it is highly recommended to specify the default download folder in Chrome Settings and disable the Select Destination option in Chrome Settings as well. This will save you a lot of time! Additionally you may want you specify the folder where these files will go to:
c1. Click on Select All checkbox to select all files from the Download List.
c2. Click on the Download button in the bottom right corner of the SMD extension window. It will take you to next tab to start downloading
c3. Hit Start selected. This will download all vids automatically into the download folder.
That is it! Simply wait till all files are downloaded and you can watch them via the VLC Player or any other player that supports the .ts format. However, if you want to have one video instead of those you have downloaded, you need to join all these mini-videos together
Joining Videos Part
Since I am working on Mac, I am not aware of how you would do this on Windows. If you are the Windows user and you want to merge the videos, feel free to google for the windows solution. The next steps are applicable for Mac only.
Open Terminal in the folder you want the new video to be saved in
Type: cat and hit space
Open the folder where you downloaded your .ts video. Select all .ts videos that you want to join (use your mouse or cmd+A)
Drag and drop them into the terminal
Hit space
Hit >
Hit Space
Type the name of the new video, e.g. my_new_video.ts. Please note that the format has to be the same as in the original videos, otherwise it will take long time to convert and even may fail!
Hit Enter. Wait for the terminal to finish the joining process and enjoy watching your video!
Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:
function blobToDataURL(blob, callback) {
var fileReader = new FileReader();
fileReader.onload = function(e) {callback(e.target.result);}
fileReader.readAsDataURL(blob);
}
I'm very late to the party.
If you want to download the content you can simply use fetch now
fetch(blobURL)
.then(res => res.blob())
.then(blob => /*do what you want with the blob here*/)
Here the solution:
let blob = new Blob(chunks, { 'type' : 'video/mp4;' });
let videoURL = window.URL.createObjectURL(blob);
const blobF = await fetch(videoURL).then(res => res.blob())
As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.
However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.
<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>
Insert this to the page containing blob url and click the button, you get the content.
Another way is to intercept the ajax call via a proxy server, then you could view the true image url.

How do I change a filename on-download with javascript?

The script adds a download link for videos (on a specific site). How do I change the filename to something else while downloading?
Example URL:
"http://website.com/video.mp4"
Example of what I want the filename to be saved as during download:
"The_title_renamed_with_javascript.mp4"
This actually is possible with JavaScript, though browser support would be spotty. You can use XHR2 to download the file from the server to the browser as a Blob, create a URL to the Blob, create an anchor with its href property set to that URL, set the download property to whatever you want the filename to be, and then click the link. This works in Google Chrome, but I haven't verified support in other browsers.
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest(),
a = document.createElement('a'), file;
xhr.open('GET', 'someFile', true);
xhr.responseType = 'blob';
xhr.onload = function () {
file = new Blob([xhr.response], { type : 'application/octet-stream' });
a.href = window.URL.createObjectURL(file);
a.download = 'someName.gif'; // Set to whatever file name you want
// Now just click the link you created
// Note that you may have to append the a element to the body somewhere
// for this to work in Firefox
a.click();
};
xhr.send();
You can't do this with client-side JavaScript, you need to set the response header...
.NET
Response.AddHeader("Content-Disposition", "inline;filename=myname.txt")
Or PHP
header('Content-Disposition: inline;filename=myname.txt')
Also available in other server-side languages of your choice.
The filename for downloading is set in the header (take a look at "Content-Disposition"), wich is created on server-side.
There's no way you could change that with pure javascript on a file you're linking to unless you have access to the server-side (that way you could pass an additional parameter giving the filename and change the server-side behaviour to set the header to match that... but that would also be possible with pure html, no need for javascript). Conclusion: Javascript is absolute useless to achive what you want.
You can probably do this with a Chrome userscript, but it cannot be done (yet) with Greasemonkey (Firefox) javascript.
Workaround methods (easiest to hardest):
Add the links with Greasemonkey but use the excellent DownThemAll! add-on to download and rename the videos.
Download the videos as-is and use a batch file, shell-script, Python program, etc. to rename them.
Use Greasemonkey's GM_xmlhttpRequest()Doc function to send the files to your own web application on a server you control.
This server could be your own PC running XAMPP (or similar).
Write your own Firefox add-on, instead of a Greasemonkey script. Add-ons have the required privileges, Greasemonkey does not.
AFAIK, you will not be able to do this right from the client itself. You could first upload the file onto the server with the desired name, and then serve it back up to the end user (in which case your file name would be used).
Just in case you are looking for such a solution for your nasty downloading chrome extension, you should look into chrome.downloads API, it needs additional permission ('downloads') and allows you to specify filename. https://developer.chrome.com/extensions/downloads
However there is a problem I'm facing right now. The chrome extension I'm refactoring has 600k+ user base and adding a new permission would disable the extension for all of them. So it is no-go solution for me, but if you are developing a new extension you definitely should use it.

Categories

Resources