为了我的项目目的,我创建了这个脚本,我认为它也适用于您或其他遇到IE11和URL方法支持不足问题的人。
if (typeof window.URL !== 'function') {
window.URL = function (url) {
var protocol = url.split('//')[0],
comps = url.split('#')[0].replace(/^(https\:\/\/|http\:\/\/)|(\/)$/g, '').split('/'),
host = comps[0],
search = comps[comps.length - 1].split('?')[1],
tmp = host.split(':'),
port = tmp[1],
hostname = tmp[0];
search = typeof search !== 'undefined' ? '?' + search : '';
var params = search
.slice(1)
.split('&')
.map(function (p) { return p.split('='); })
.reduce(function (p, c) {
var parts = c.split('=', 2).map(function (param) { return decodeURIComponent(param); });
if (parts.length == 0 || parts[0] != param) return (p instanceof Array) && !asArray ? null : p;
return asArray ? p.concat(parts.concat(true)[1]) : parts.concat(true)[1];
}, []);
return {
hash: url.indexOf('#') > -1 ? url.substring(url.indexOf('#')) : '',
protocol: protocol,
host: host,
hostname: hostname,
href: url,
pathname: '/' + comps.splice(1).map(function (o) { return /\?/.test(o) ? o.split('?')[0] : o; }).join('/'),
search: search,
origin: protocol + '//' + host,
port: typeof port !== 'undefined' ? port : '',
searchParams: {
get: function(p) {
return p in params? params[p] : ''
},
getAll: function(){ return params; }
}
};
}
}
if( typeof window.URL !== 'function' ){
window.URL = function(url){
let protocol = url.split('//')[0],
comps = url.split('#')[0].replace(/^(https\:\/\/|http\:\/\/)|(\/)$/g, '').split('/'),
host = comps[0],
search = comps[comps.length - 1].split('?')[1],
tmp = host.split(':'),
port = tmp[1],
hostname = tmp[0];
search = typeof search !== 'undefined'? '?' + search : '';
const params = search
.slice(1)
.split('&')
.map(p => p.split('='))
.reduce((obj, pair) => {
const [key, value] = pair.map(decodeURIComponent);
return ({ ...obj, [key]: value })
}, {});
return {
hash: url.indexOf('#') > -1? url.substring(url.indexOf('#')) : '',
protocol,
host,
hostname,
href: url,
pathname: '/' + comps.splice(1).map(function(o){ return /\?/.test(o)? o.split('?')[0] : o; }).join('/'),
search,
origin: protocol + '//' + host,
port: typeof port !== 'undefined'? port : '',
searchParams: {
get: p => p in params? params[p] : '',
getAll: () => params
}
};
}
}
new URL('http://localhost:8080/?a=1&b=3&c=z#123').searchParams.get('c');
但如果这个方法对你不起作用的话,你可以从这个网址中获取完全支持和填充的函数:
https://www.npmjs.com/package/url-polyfill
window.URL
仅在 Edge(以及所有非 IE 浏览器)中可用。 - Andreas