Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose between `window.URL.createObjectURL()` and `window.webkitURL.createObjectURL()` based on browser

From the Firefox developer website, I know that Firefox uses

objectURL = window.URL.createObjectURL(file);

to get url of file type, but in chrome and other webkit browsers we have window.webkitURL.createObjectURL() for detecting url.

I don't know how to swap this functions based on browser engines, and I need it to be worked on both browsers (Chrome and firefox)

https://developer.mozilla.org/en/DOM/window.URL.createObjectURL

like image 975
Rohith Raveendran Avatar asked Jun 30 '12 21:06

Rohith Raveendran


People also ask

What is window URL createObjectURL?

createObjectURL() The URL. createObjectURL() static method creates a string containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.

Is createObjectURL deprecated?

The URL. createObjectURL() method has been removed from the MediaStream interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.

What does URL createObjectURL return?

createObjectURL is a static method provided by the URL Web API. Returns a DOMString containing a unique blob URL, that is a URL with blob: as its scheme, followed by an opaque string uniquely identifying the object in the browser.


2 Answers

You could define a wrapper function:

function createObjectURL ( file ) {
    if ( window.webkitURL ) {
        return window.webkitURL.createObjectURL( file );
    } else if ( window.URL && window.URL.createObjectURL ) {
        return window.URL.createObjectURL( file );
    } else {
        return null;
    }
}

And then:

// works cross-browser
var url = createObjectURL( file );
like image 68
Šime Vidas Avatar answered Sep 22 '22 22:09

Šime Vidas


Simple one liner:

var createObjectURL = (window.URL || window.webkitURL || {}).createObjectURL || function(){};
like image 36
Trevor Avatar answered Sep 19 '22 22:09

Trevor