Подтвердить что ты не робот

новый URL (location.href) не работает в IE

Я столкнулся с проблемой с новым URL-адресом метода ("адресом") в IE.

У меня есть этот код:

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

В Firefox и Chrome он работает при условии, и я получу значение атрибута "api".

Но в IE я получаю ошибку на консоли:

SCRIPT445: объект не поддерживает это действие

Отладчик ошибок консоли указывает на проблему с линией

var hrefParams = new URL(href);

Для решения другой проблемы я уже вызываю скрипт

<script type="text/javascript" src="js/bluebird.min.js"></script>

Но это не устраняет эту проблему.

Любая идея, как исправить это в IE?

4b9b3361

Ответ 1

В конце я исправил это по этому коду:

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');

Я забыл, где я нашел это, но он работает так, как мне было нужно.

Ответ 2

IE не поддерживает URL. Вам придется добавить для него полипол.

Ответ 3

Другое решение, которое я использовал, если кому-то интересно

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');

Ответ 4

Этот метод не поддерживается IE

См. Https://developer.mozilla.org/en-US/docs/Web/API/URL#AutoCompatibilityTable.

вы должны использовать lib как jquery deparam или получить параметры с помощью метода String.split() или использовать эту функцию, которую я сделал:

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'))

Ответ 5

Чистое решение Javascript, так что вы можете запустить его в IE, не беспокоясь о polyfills:

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

Приходит с этой страницы: https://html-online.com/articles/get-url-parameters-javascript/

Ответ 6

Добавить polyfill polyfill cdn

<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>