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

后端 未结 9 1634
心在旅途
心在旅途 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: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'))

提交回复
热议问题