109

What is the difference between window.location.assign() and window.location.replace(), when both redirect to a new page?

user2428118
  • 7,499
  • 4
  • 41
  • 69
Bakudan
  • 17,636
  • 9
  • 48
  • 69

4 Answers4

133

Using window.location.assign("url") will just cause a new document to load. Using window.location.replace("url") will replace the current document and replace the current History with that URL making it so you can't go back to the previous document loaded.

Reference: http://www.exforsys.com/tutorials/javascript/javascript-location-object.html

Bakudan
  • 17,636
  • 9
  • 48
  • 69
RedAnthrax
  • 1,494
  • 1
  • 9
  • 4
37

The difference is how history is handled. "Replace" won't give you history, "assign" will.

martona
  • 4,990
  • 1
  • 15
  • 18
31

According to MDN:

The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Community
  • 1
  • 1
Matt Ball
  • 332,322
  • 92
  • 617
  • 683
12
  1. location.assign():

    To assign route path by passing path into it. Assign will give you a history even after path was assigned.

    Usage Method: Value should be passed into it.

    Eg: location.assign("http://google.com")

location.assign()

  1. location.replace():

    It helps to replace path if you don't want to keep history. It won't give you a history once you replace its path.

    Usage Method: Value should be passed into it.

    Eg: location.replace("http://google.com")

location.repalce()

N'Bayramberdiyev
  • 4,947
  • 7
  • 18
  • 39
Mohideen bin Mohammed
  • 14,471
  • 7
  • 86
  • 95