web-dev-qa-db-fra.com

nouvelle URL (location.href) ne fonctionne pas dans IE

Je suis confronté à un problème de méthode nouvelle adresse URL ('adresse') dans IE.

J'ai ce code:

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

Dans Firefox et Chrome cela fonctionne à devrait et je vais obtenir la valeur d'attribut "api".

Mais dans IE, je reçois une erreur sur la console:

SCRIPT445: L'objet ne supporte pas cette action

Le débogueur d'erreur de la console pointe vers le problème avec la ligne 

var hrefParams = new URL(href);

Pour résoudre un autre problème, j'invoque déjà un script 

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

Mais cela ne résout pas ce problème. 

Une idée de comment résoudre ce problème dans IE?

9
Reddy SK

A la fin, j'ai corrigé cela avec ce 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');

J'ai oublié où j'ai trouvé ça, mais ça fonctionne comme j'avais besoin. 

12
Reddy SK

IE ne supporte pas URL. Vous devrez ajouter un polyfill pour cela.

3
Daniel A. White

Cette méthode n'est pas supportée par IE 

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

vous devriez utiliser une lib comme jquery deparam ou récupérer les paramètres avec la méthode String.split () ou utiliser cette fonction que j'ai créée:

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

3
Alex83690

Une autre solution que j'utilise si quelqu'un est intéressé

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

Solution Javascript pure, vous pouvez donc l'exécuter dans IE également sans vous soucier des polyfills:

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

Provient de cette page: https://html-online.com/articles/get-url-parameters-javascript/

0
Ales