Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do nothing if local storage variable is empty

Tags:

javascript

I am using the script below to append utm parameters to the end of a page's URL. However, sometimes there will be no parameters, thus meaning nothing in the local storage variable.

The problem: when there is nothing in local storage, it currently appends ?null to the end of the URL.

<script type="text/javascript">
  // Get parameters from local storage
  var parameters = localStorage.getItem("query");

  if(window.location.href.indexOf('?' + parameters) == -1){

    // Identify next URL
    const nextURL = window.location.href + '?' + parameters;

    // Replace current entry in browser history
    window.history.replaceState('', '', nextURL);
  }
</script>

1 Answers

You can check if the local storage variable is empty.

Using your example, you could change it to this:

<script type="text/javascript">
  // Get parameters from local storage
  var parameters = localStorage.getItem("query");

  if (!parameters) return; // <--- you could add this line.

  if(parameters && // <---- or add this condition
      window.location.href.indexOf('?' + parameters) == -1){

    // Identify next URL
    const nextURL = window.location.href + '?' + parameters;

    // Replace current entry in browser history
    window.history.replaceState('', '', nextURL);
  }
</script>
like image 196
calvin Avatar answered Jun 08 '26 00:06

calvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!