Update JS modify URL article
This commit is contained in:
@ -6,12 +6,12 @@ authors: chalarangelo
|
||||
cover: blog_images/compass.jpg
|
||||
excerpt: Learn all of the options JavaScript provides for modifying the URL of the current page in the browser without reloading the page.
|
||||
firstSeen: 2020-03-27T13:48:27+02:00
|
||||
lastUpdated: 2021-06-12T19:30:41+03:00
|
||||
lastUpdated: 2021-09-27T16:47:49+03:00
|
||||
---
|
||||
|
||||
### Using the History API
|
||||
|
||||
The HTML5 [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) is definitely the way to go for modern websites, as it accomplishes the task at hand, while also providing additional functionality. You can use either `history.pushState()` or `history.replaceState()` to modify the URL in the browser, depending on your needs:
|
||||
The HTML5 [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) is definitely the way to go for modern websites. It accomplishes the task at hand, while also providing additional functionality. You can use either `history.pushState()` or `history.replaceState()` to modify the URL in the browser, depending on your needs:
|
||||
|
||||
```js
|
||||
// Current URL: https://my-website.com/page_a
|
||||
@ -30,7 +30,7 @@ The arguments for both methods are the same, allowing you to pass a customized s
|
||||
|
||||
### Using the Location API
|
||||
|
||||
The older [Location API](https://developer.mozilla.org/en-US/docs/Web/API/Location) is not the best tool for the job, as it reloads the page, however it still allows you to modify the current URL and might be useful when working with legacy browsers. You can modify the URL, using either `window.location.href`, `location.assign()` or `location.replace()`:
|
||||
The older [Location API](https://developer.mozilla.org/en-US/docs/Web/API/Location) is not the best tool for the job. It reloads the page, but still allows you to modify the current URL and might be useful when working with legacy browsers. You can modify the URL, using either `window.location.href`, `location.assign()` or `location.replace()`:
|
||||
|
||||
```js
|
||||
// Current URL: https://my-website.com/page_a
|
||||
@ -46,4 +46,4 @@ window.location.assign(nextURL);
|
||||
window.location.replace(nextURL);
|
||||
```
|
||||
|
||||
As you can see, all three options will cause a page reload, which can be undesirable. Additionally, you can only set the URL, without any additional arguments, unlike using the History API. Finally, the Location API doesn't restrict you to same-origin URLs, which can be the cause of security issues if you are not careful.
|
||||
As you can see, all three options will cause a page reload, which can be undesirable. Unlike the History API, you can only set the URL, without any additional arguments. Finally, the Location API doesn't restrict you to same-origin URLs, which can cause security issues if you are not careful.
|
||||
|
||||
Reference in New Issue
Block a user