简体   繁体   中英

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

简单的一个班轮:

var createObjectURL = (window.URL || window.webkitURL || {}).createObjectURL || function(){};

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 );
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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM