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

3 Answers 3

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 );
1
  • 6
    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
    Commented Mar 18, 2017 at 8:44
25

Simple one liner:

var createObjectURL = (window.URL || window.webkitURL || {}).createObjectURL || function(){};
2
  • 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. Commented Jun 30, 2012 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
    Commented Jun 30, 2012 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;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.