15

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

kmonsoor
  • 7,600
  • 7
  • 41
  • 55
Rohith Raveendran
  • 410
  • 1
  • 6
  • 14

3 Answers3

26

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 );
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • 5
    I think this is not anymore necessary as when I used this in the code Chrome return "webkitURL' is deprecated. Please use 'URL' instead." message in the console. – Wenuka Mar 18 '17 at 08:44
25

Simple one liner:

var createObjectURL = (window.URL || window.webkitURL || {}).createObjectURL || function(){};
Trevor
  • 9,518
  • 2
  • 25
  • 26
  • 1
    If the `createObjectURL` method doesn't exist in the browser, the variable will be `undefined`, and trying to invoke it will throw an error. – Šime Vidas Jun 30 '12 at 21:21
  • @ŠimeVidas That is correct but wasn't part of the question. It is now fixed in a way that won't have any overhead for each additional call. – Trevor Jun 30 '12 at 21:22
9
if (window.URL !== undefined) {
    window.URL.createObjectURL();
} else if (window.webkitURL !== undefined) {
    window.webkitURL.createObjectURL();
} else {
    console.log('Method Unavailable: createObjectURL');
}

Is round-about what you're looking for. Also, THIS example uses the much simpler...

window.URL = window.URL || window.webkitURL;
65Fbef05
  • 4,492
  • 1
  • 22
  • 24