ChromeとFirefoxはdocument.location.href
URLエンコードされて保存されますが、IE9はエンコードされていない状態で保存されます。
例えば:
- Chrome / 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)
することは十分に安全であるように思われますが、そこにある最良の解決策ではありません。これをよりエレガントに処理する方法について何か提案はありますか?