安全地对hrefs进行URL编码(不知道是否已编码!)

时间:2012-10-22 18:39:26

标签: javascript cross-browser urlencode

我注意到Chrome和Firefox存储document.location.href网址编码,而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)似乎足够安全但不能成为最好的解决方案..有任何建议如何处理这个更优雅?

1 个答案:

答案 0 :(得分:0)

怎么样:

encodeURIComponent("http://asdf.com?foo=bar&bla=asdfäöü");
"http%3A%2F%2Fasdf.com%3Ffoo%3Dbar%26bla%3Dasdf%C3%A4%C3%B6%C3%BC"

encodeURI("http://asdf.com?foo=bar&bla=asdfäöü");
"http://asdf.com?foo=bar&bla=asdf%C3%A4%C3%B6%C3%BC"