55

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

wpp
  • 7,093
  • 4
  • 33
  • 65
Narayan Adhikari
  • 1,514
  • 1
  • 10
  • 14

6 Answers6

90

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&param2=&id=6"

$.urlParam('param1');  // name
$.urlParam('id');      // 6
$.urlParam('param2');  // null
wpp
  • 7,093
  • 4
  • 33
  • 65
Narayan Adhikari
  • 1,514
  • 1
  • 10
  • 14
  • Hi there I don't understand how you have managed to assign the value 'name' to the parameter 'param1', same for all the others parameter. Can you please explain that? In my case I have: `var parameters = new URLSearchParams(); and a function setProfile(value){ parameters.append("ProfileId", value); }` Thanks – Daniele Nov 20 '19 at 17:28
  • I don't really understand how people are able to find solutions in Regex. Thanks a lot! Saved my time. – Naseem Ahamed Sep 23 '21 at 11:59
40

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)
Andy Taw
  • 2,794
  • 1
  • 17
  • 9
  • 1
    Good because does not create a new function but implements missing one, so copy-paste should work for everyone. – Adam Bubela Jan 25 '19 at 15:58
  • Using `decodeURIComponent` instead of `decodeURI` is a more complete solution, I'd say. – Štěpán Aug 06 '19 at 08:52
  • 1
    I like this approach however if you need to use append (i.e. `URLSearchParams.append()` it doesn't work. – Brent O'Connor Nov 20 '19 at 17:25
  • 1
    Hence 'partial'. – Andy Taw Nov 21 '19 at 18:12
  • 1
    You can add support for the `has()` method to @AndyTaw's answer by adding this under the self.get definition: `self.has = function (name) { var results = new RegExp('[\?&]' + name).exec(self.searchString); if (results == null) { return null; } else { return true; }}` and you can add support for other methods (like `append()` as needed in a similar manner. – Rick Gladwin Jul 10 '20 at 17:06
20

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

aTON
  • 25
  • 6
akuji1993
  • 381
  • 3
  • 9
10

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!

Laura Mann
  • 101
  • 1
  • 4
2

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();
CAMD_3441
  • 2,514
  • 2
  • 23
  • 38
0
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;
  • 1
    This will not work on IE, how the question specifically asks for. No version of IE supports Class or Arrow function. Not to speak of the 'export default'. It's good code otherwise,except for a missing encodeURIComponent on setURL. – Jk041 Sep 03 '21 at 11:26