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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With