new URL(location.href) doesn't work in IE

后端 未结 9 1624
心在旅途
心在旅途 2020-12-10 23:52

I am facing to problem with method new URL(\'address\') in IE.

I have this code:

var href =  location.href;
var hrefParams = new URL(href);
var api =         


        
相关标签:
9条回答
  • 2020-12-11 00:37

    IE does not support URL. You will have to add a polyfill for it.

    0 讨论(0)
  • 2020-12-11 00:37

    Add polyfill cdn script

    <script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
    
    0 讨论(0)
  • 2020-12-11 00:41

    Another solution I've been using if anyone is interested

    function getParameterByName(name) {
      name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
      var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
          results = regex.exec(location.search);
      return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    
    getParameterByName('api');
    
    0 讨论(0)
  • 2020-12-11 00:45

    Pure Javascript solution, so you can run it in IE as well without bothering with polyfills:

       function getUrlVars() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                vars[key] = value;
            });
            return vars;
        }
    

    Comes from this page: https://html-online.com/articles/get-url-parameters-javascript/

    0 讨论(0)
  • 2020-12-11 00:48

    This method is not supported by IE

    See https://developer.mozilla.org/en-US/docs/Web/API/URL#AutoCompatibilityTable

    you should use a lib like jquery deparam or retrieve the parameters with String.split() method or use this function that I made:

    function decodeUriComponentWithSpace (component) {
        return decodeURIComponent(component.replace(/\+/g, '%20'))
      }
    
      // type : 'hash', 'search' or 'both'
      function getLocationParameters (location, type) {
        if (type !== 'hash' && type !== 'search' && type !== 'both') {
          throw 'getLocationParameters expect argument 2 "type" to be "hash", "search" or "both"'
        }
    
        let searchString = typeof location.search === 'undefined' ? '' : location.search.substr(1)
        let hashString = typeof location.hash === 'undefined' ? '' : location.hash.substr(1)
        let queries = []
        if (type === 'search' || type === 'both') {
          queries = queries.concat(searchString.split('&'))
        }
        if (type === 'hash' || type === 'both') {
          queries = queries.concat(hashString.split('&'))
        }
    
        let params = {}
        let pair
    
        for (let i = 0; i < queries.length; i++) {
          if (queries[i] !== '') {
            pair = queries[i].split('=')
            params[this.decodeUriComponentWithSpace(pair[0])] = this.decodeUriComponentWithSpace(pair[1])
          }
        }
        return params
    }
    
       // TEST: 
    window.location.hash = 'test=a&test2=b'
    console.log(getLocationParameters(window.location, 'both'))

    0 讨论(0)
  • 2020-12-11 00:51

    For the purposes of my project, I've created this script, which I think also could work for you or someone else who has a problem with IE11 and the lack of support for the URL method.

            /* Polyfill URL method IE 11 */
    
            // ES5
    
            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; }
                        }
                    };
                }
            }
    
            // ES6, in case of using Babel in a project
    
            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
                        }
                    };
                }
            }
            /* Polyfill IE 11 end */
    
            new URL('http://localhost:8080/?a=1&b=3&c=z#123').searchParams.get('c'); // this will return "z"
    

    But if it doesn't work for you, you could take I think full suported and polifilled function from this package here on the url:

    https://www.npmjs.com/package/url-polyfill

    0 讨论(0)
提交回复
热议问题