0

I have some parameters in url that are added when coming to a specific page, so correct page is opened. For example: https://example.com/index.php?cCode=SFI=&cmpn=cHJvdmlkaW8= Now, when i get to that page, i want to remove them, so they don't get passed further, but still want to keep any additional parameters, like source=facebook or whatever... I found a way to remove them with this code:

var urlParts = url.split('?');
var params = new URLSearchParams(urlParts[1]);
params.delete('cCode');
params.delete('cmpn');
var newUrl = urlParts[0] + '?' + params.toString();
history.pushState(null, null, newUrl);

But they still get forwarded when i click on a some link... Any way to do this, with js or even php?

Gimli
  • 29
  • 3
  • Does this answer your question? [How can I delete a query string parameter in JavaScript?](https://stackoverflow.com/questions/1634748/how-can-i-delete-a-query-string-parameter-in-javascript) – Robin Singh Dec 24 '20 at 06:36
  • I have found out that the code i use actually works, it looks like i have some conflict on the site i am working on specifically – Gimli Dec 24 '20 at 06:56

1 Answers1

0

I would recommend using the URL object instead of the url string.

let url = new URL(window.location.href);
url.searchParams.delete('cCode');
url.searchParams.delete('cmpn');
window.history.pushState({}, document.title, url);

Be advised, the URL object is not supported on IE.

Refer to this url polyfill for IE compatability.

https://www.npmjs.com/package/url-polyfill

  • Yes, this works also, as the code i originally used, it is just a problem with this one site, for some reason it is not working on it, but multiple people worked on it, so i have to check all... TY – Gimli Dec 24 '20 at 07:40
  • Maybe the query params are being enforced via php on the server side. Good luck! – Jason Kirshner Dec 24 '20 at 19:47