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

后端 未结 9 1633
心在旅途
心在旅途 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:52

    At the end I have fixed that by this code:

    function getQueryString() {
              var key = false, res = {}, itm = null;
              // get the query string without the ?
              var qs = location.search.substring(1);
              // check for the key as an argument
              if (arguments.length > 0 && arguments[0].length > 1)
                key = arguments[0];
              // make a regex pattern to grab key/value
              var pattern = /([^&=]+)=([^&]*)/g;
              // loop the items in the query string, either
              // find a match to the argument, or build an object
              // with key/value pairs
              while (itm = pattern.exec(qs)) {
                if (key !== false && decodeURIComponent(itm[1]) === key)
                  return decodeURIComponent(itm[2]);
                else if (key === false)
                  res[decodeURIComponent(itm[1])] = decodeURIComponent(itm[2]);
              }
    
              return key === false ? res : null;
    }
    

    ...

            var api = getQueryString('api');
    

    I forgot where I found that but it is working as I needed.

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

    Here's another polyfill specifically for the URL api, intended to work exactly as it does in modern browsers and only run if needed. This way you don't need to use a separate function that will be obsolete once you decide to drop support for IE.

    <script src="https://gist.github.com/RyanG26/def0a520ed43c6c465d9a6518161bc7c.js"></script>

    Gist Page: https://gist.github.com/RyanG26/def0a520ed43c6c465d9a6518161bc7c

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

    modified @ales code for getting the value of a particular parameter. The default value is set to false.

    function getUrlVars(index) {
      var vars = {};
      window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (
        m,
        key,
        value
      ) {
        vars[key] = value;
      });
    
      if (index) {
        return vars[index] || false;
      }
      return vars;
    }
    
    0 讨论(0)
提交回复
热议问题