Windows.location. and the property that stores the location is
href. For example, the current location of a page can be obtained as follows:
let paginaActual = location.href; console.log( paginaActual );
Then, to change that location and therefore redirect the current page, we just set a new location:
location.href = 'target URL';
But in practice this code would not be the best user experience.
When it is necessary to make a redirect the most likely reason is that there was a change (domain, content, importance), then to give a better user experience we could:
- Wait for the page to load.
- Display a message that the content has changed location and wait x seconds for it to be read.
- Execute the redirection.
This can be done with this code:
Where you need to replace:
- https://blogandweb.com – With your destination URL, the new URL. Don’t forget to add the protocol:
https://. Other uses: You can redirect to an email: Example: “mailto:email@example.com”. Or to an anchor on the page. Example: “#footer”.
- 5 – With the number of seconds before executing the redirection. It can be 0 so that there is no timeout.
location.href is a very old property and well supported by all browsers. You can use it with peace of mind in production.