0

I am able to redirect/replace the url from the below code

function replceUrl(){
  window.location.assign("https://www.example.com");
  event.preventDefault();
}

After replacing the url, I want to stop page reload. I have added event.preventDefault(), but the page still reloads.

How to prevent page reload after replacing the url is the challenge

terrymorse
  • 6,771
  • 1
  • 21
  • 27
Blaze
  • 2,269
  • 11
  • 40
  • 82

1 Answers1

0

event.preventDefault() won't help you there, its purpose is to prevent the default behavior of the event that fired the function.

You won't be able to change the URL without reloading the page unless you use History API or window.location.hash

History API will let you change the last URL segment without reloading the page with this code: history.pushState({some: 'data'}, "New title", "new-url-segment") while window.location.hash = 'something' will let you change the URL fragment.

Note that the URL fragment's original purpose is to create links that scrolls to a specific id in the page once it's loaded.

Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • so can u modify the answer using the history api as suggested – Blaze May 26 '20 at 16:58
  • this approach does not over write the url completely, I do not just want to over write the url fragment – Blaze May 26 '20 at 17:07
  • @Blaze Have you even gone through any answer in the suggested duplicate? – Anurag Srivastava May 26 '20 at 17:08
  • sure and its same with Guerric answer, u can extract from ur suggestion and post here, please – Blaze May 26 '20 at 17:10
  • Yes, but it's the best thing you can do, you won't be able to manually change the full URL without reloading the page, and you won't be able to do it programmatically either. Imagine you could impersonate google.com by copying their website, hosting it on your own domain, then changing the URL with JavaScript! – Guerric P May 26 '20 at 17:15