SCRIPT5009: 'URLSearchParams' is undefined in IE 11

Jquery

Jquery Problem Overview


I'm trying to execute the URLSearchParams but I get an error on IE 11 since it is not supported there. It's working perfectly in Chrome and Firefox.

How can I get the equivalent functionality in IE 11? I am executing the code in Laravel 5.4.

Here is the line of code which I'm trying to execute.

var urlParams = new URLSearchParams(window.location.search);

Error:

> SCRIPT5009: 'URLSearchParams' is undefined

Jquery Solutions


Solution 1 - Jquery

Got a solution by replacing the code with the following:

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null){
       return null;
    }
    else {
       return decodeURI(results[1]) || 0;
    }
}

So for example "example.com?param1=name¶m2=&id=6"

$.urlParam('param1');  // name
$.urlParam('id');      // 6
$.urlParam('param2');  // null

Solution 2 - Jquery

Odhikari's answer as a (partial) polyfill:

(function (w) {

    w.URLSearchParams = w.URLSearchParams || function (searchString) {
        var self = this;
        self.searchString = searchString;
        self.get = function (name) {
            var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(self.searchString);
            if (results == null) {
                return null;
            }
            else {
                return decodeURI(results[1]) || 0;
            }
        };
    }

})(window)

Solution 3 - Jquery

If anyone finds this in 2019, corejs now also supports URLSearchParams as a polyfill, so you can just stay with corejs and don't have to brew together something yourselves.

import 'core-js/features/url-search-params';

https://github.com/zloirock/core-js#url-and-urlsearchparams

Solution 4 - Jquery

I was able to solve this by using url-search-params-polyfill. Just import into the file you're using URLSearchParams in:

import 'url-search-params-polyfill';

And your existing references to URLSearchParams should now work!

Solution 5 - Jquery

I have had a similar issue when trying to use URLSearchParams when trying to make an AXIOS Post when using Internet Explorer. So its a little different from your description, but I'd like to post my resolution here just in case.

Here's my AXIOS post code from my React app that works just fine for Edge, Chrome and Firefox, but on IE it gives me the error

> SCRIPT5009: URLSearchParams is undefined

:

        let axiosConfig = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };            
        // Putting together the data to be passed to local servlet.
        const params = new URLSearchParams();
        params.append('var1', this.state.data1);
        params.append('var2', this.state.data2);

        var urlToPost = 'https://localhost:8080/someLocalServlet/doSomething';

        var self = this;  
        axios.post(urlToPost, params, axiosConfig)
            .then((res) => {
                // Handling Response from Servlet.
                console.log("AXIOS POST RESPONSE RECEIVED: ", res);

            })
            .catch((err) => {
                // Handler exception error thrown by Servlet.
                console.log("AXIOS POST ERROR: ", err);

            })     

To get it to work with IE I used jQuery to do the Post and used a var object instead of URLSearchParams. The if statement below checks to see if the user is on IE :

    if((navigator.userAgent.indexOf("MSIE") !== -1 ) || (!!document.documentMode === true )) { //IF IE > 10
        var myObject = {
            var1: this.state.data1,
            var2: this.state.data2
        };
        var urlToPostTo = 'https://localhost:8080/someLocalServlet/doSomething';

        $.post(urlToPost, myObject, 
            function(result) {  
                alert( "success" );
            })
              .done(function(result) {
                alert( "second success" );
              })
              .fail(function(result) {
                alert( "error" );
              })
              .always(function(result) {
                    alert( "finished" );
              });        
    } else {
       // use the AXIOS POST code above
    }

To get the jQuery, I did have to do

> npm install jquery

Then on top of my React file I imported the following:

import $ from 'jquery'; 
import { polyfill } from 'es6-promise'; polyfill();

Solution 6 - Jquery

class UrlSearchParams {
  constructor(query) {
    this.query = query;
  }
  getSearchObject = () => {
    const { query } = this;
    return query
    ? (/^[?#]/.test(query) ? query.slice(1) : query)
      .split("&")
      .reduce((params, param) => {
        let [key, value] = param.split("=");
        params[key] = value
          ? decodeURIComponent(value.replace(/\+/g, " "))
          : "";
        return params;
      }, {})
  : {};
  };
  getAll = () => {
    const searchParams = this.getSearchObject();
    return searchParams;
  }
  get = param => {
    const searchParams = this.getSearchObject();
    return searchParams[param];
  };
  setUrl = (param, value) => {
    const searchParams = this.getSearchObject();
    searchParams[param] = value;
    return Object.keys(searchParams)
    .map(key => key + "=" + searchParams[key])
    .join("&");
  };
}

export default UrlSearchParams;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNarayan AdhikariView Question on Stackoverflow
Solution 1 - JqueryNarayan AdhikariView Answer on Stackoverflow
Solution 2 - JqueryAndy TawView Answer on Stackoverflow
Solution 3 - Jqueryakuji1993View Answer on Stackoverflow
Solution 4 - JqueryLaura MannView Answer on Stackoverflow
Solution 5 - JqueryCAMD_3441View Answer on Stackoverflow
Solution 6 - JqueryBulut AğırmanView Answer on Stackoverflow