0

Goal: Omit the id param from my page AND able to reload the current page.

Original URL: www.onecompany.com/dept?id=12345&name=myName

I was able to get the modified url.

Modified URL: www.onecompany.com/dept?name=myName

I used this code:

window.history.pushState(null, null, modifiedUrl);

And the page load successfully without the id param. But when I refresh the page (I want to reload the current page), it did not load

www.onecompany.com/dept?id=12345&name=myName

but it load this

www.onecompany.com/dept?name=myName

When I attempted

window.history.pushState(null, null, originalUrl);

The refresh works but one part of my goal is failed, not omit the id param.

I am lost in a circle.

My question: Is it possible to load my page (with id param omitted) AND able to refresh the page (to load the correct page without id param)?

Thanks for any advice !

1 Answers1

0

I guess, you're trying to hide the information 'id' for the user. I would recommend to use cookies to save the information 'id'.

Otherwise:

//Example: 'www.onecompany.com/dept?id=12345&name=myName'

var query = window.location.search;
var oldquery = window.location.search;
query = query.replace(/id=\d+&?/i, '');
console.log(query);
//Out: ?name=myName

window.history.pushState(null, null, query); //then hide the id

You have to change the URL back to the original, before the user leaves the website. This will not work.

But if youre willing to do, you could listen for the window.onbeforeunload event and change the query back again to oldquery. See here: Handle refresh page event with javascript - But there are a lot of differences between browsers, on how they will process the window.unbeforeunload event. They will usually not allow to do that.

Sascha
  • 36
  • 5