我注意到 Chrome 和 Firefox 存储document.location.href
URL 编码,而 IE9 存储它未编码。
例如:
- 铬/FF:
http://domain.tld/some%20folder/
- IE:
http://domain.tld/some folder/
有什么约定吗?更重要的是,有没有一种可靠的方法可以在不检查供应商的情况下检查它是否是 URL 编码的?
我目前的解决方案是:
// helpers
var reUriToPathname = /^.*:\/\/[^\/]*|[^\/]*$/g,
uriToPathname = function (uri) {
return uri.replace(reUriToPathname, '');
},
forceEncoding = function (href) {
// collection of manual fixes..
return href
.replace(/\/+/g, '/')
.replace(/ /g, '%20')
.replace(/'/g, '%27')
.replace(/\[/g, '%5B')
.replace(/\]/g, '%5D')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\+/g, '%2B')
.replace(/\=/g, '%3D');
},
// check once with a testpath
hrefsAreDecoded = (function () {
var testpathname = '/a b',
a = doc.createElement('a');
a.href = testpathname;
return uriToPathname(a.href) === testpathname;
}()),
// safely return encoded href
getEncodedHref = function (href) {
var a = doc.createElement('a'),
location;
a.href = href;
location = uriToPathname(a.href);
if (hrefsAreDecoded) {
location = encodeURIComponent(location).replace(/%2F/ig, '/');
}
return forceEncoding(location);
};
使用getEncodedHref(document.location.href)
似乎足够安全,但不是最好的解决方案。有什么建议可以更优雅地处理这个问题吗?