Languages
[Edit]
EN

In how many ways can you redirect your web page in JavaScript?

9 points
Created by:
Laylah-Walsh
624

Some time ago I got an idea to count, in how many ways you can make redirect operation in web browser JavaScript?

 

 

It is known for a long time that, at the very beginning, browsers offered Location API (i.e. window.location object) with JS, that helps to redirect the current page to a completely different one. As an alternative to it, we can look at the existing quirks - yes quirks, you haven't heard yourself! - because that's what I am going to call link creation in order to click on it and redirect our site elsewhere. And I will tell you that I believe that there will definitely be a man who will do it :) because why not ... if it is possible, heh ... It reminds me of my little cat, who instead of going straight, tries to squeeze through a narrow crack, next to it to continue its journey - because cats have this way.

 

 

Before HTML 5 appeared, the developers who designed API put a lot of effort to provide special functions to navigate that was needed - it is the History API (i.e. window.history object). Ok, I know a lot of solutions come from suggested and already implemented solutions in many browsers. 

 

But what's new about this new API that Location API doesn't have?

 

New power?
New power?

 

heh, ok, I will explain briefly:

The History API allows us to navigate without reloading the page. But wait..., someone well versed in the subject could ask me the question: what does the History API have common with a redirect? This is a redirect for which we need to change the content by own logic in own way - which does not change the fact that the URL is changed in the browser's address field after the operation. After refreshing the page, the page associated with the new address will be load. Modern Front-end frameworks such as Angular, React, VUE, etc. use this technique. It is only covered by the Routing API provided by various types of routing modules.

Location API

Location? yes, but this is about the website address, not the server physical location: P
Location? yes, but this is about the website address, not the server physical location: P

 

It provides 3 basic approaches:

  • location.assign('http://my-new-url.com')
    navigates to the indicated page,
     
  • locartion.href = 'http://my-new-url.com'
    it is nothing more than an alternative approach to the assign() function,
     
  • location.replace('http://my-new-url.com')
    removes the current page from the history of browsed pages and inserts a new entry with opening the link - overwriting actual link in history,
     
  • okay there are still:
    location.hostname, location.pathname, location.search, e.t.c.
    but they only change a specific part of the URL so I skip it :)

With this API we can redirect our website to any link - even with other origin.

 

<!doctype html>
<html>
<body>
  <script>

    location.replace('https://dirask.com/about');
    //location.assign('https://dirask.com/about');
    //location.href = 'https://dirask.com/about';

  </script>
</body>
</html>

The technical version of the article can be found here.

 

How such an API can be used for? I think a cool and simple example could be redirect operation to the https version of my page if needed.

<!doctype html>
<html>
<head>
  <script>

    if (location.protocol === 'http') {
        location.protocol = 'https';
    }

  </script>
</head>
<body>Page content...</body>
</html>

History API

It gives you the ability to reload pages faster.

 

A small-big thing! I am sure, this feature is very useful for many developers - sometimes accessing it directly
A small-big thing!
I am sure that this feature is very useful for many developers - some of them access it directly

 

It provides the 2 most important functions:

  • history.pushState(state, title, url)
    adds another entry to the navigation history, changing url,
     
  • history.replaceState(state, title, url)
    replaces the current entry in the navigation history, changing url,

Where noteworthy:

  • url argument is the address that will be displayed in the URL field of the browser without causing the page to reload - the "small" limitation is the fact that we can only navigate within the same domain!!! and later need to overload the page content with own logic...
  • state and title arguments are described in the documentation here and here.

After refreshing our website, the source code will be loaded from the current URL - normal scenario of page loaging.

Link and simulated click action

And now it's time for quirks offered by the link itself and the click() function. Maybe I will show it on an example:

<html>
<body>
  <a id="link" href="https://dirask.com"></a>
  <script>
  
    var element = document.querySelector('#link');
    element.click();
  
  </script>
</body>
</html>

I recommend to copy the example and run it locally :)

Summary

I decided to put everything together in one table.

 RedirectReplace redirectAdvantages and disadvantages
Location API

location
  .assign(u)

location
  .href = u

location
  .replace(u)

+ Possible to navigate to any link.

~ Loss of current state? - not really, because there is a trick with hash property - this is a topic for a separate article.

History API

history
  .pushState
  (s, t, u)

history
  .replaceState
  (s, t, u)

+ Shorts web page loading time and keeps the current page state.

- You have to write source code for changing the content properly.

- Navigation only in the same domain.

Link + Click

var link = ...

link.click()

Not provided

- It is rather hacking than a good solution.

- It can be blocked by the browser.

 

Conclusions:

  • If you want to navigate, use just Location API.
  • When we want to reload only a certain part of the page and speed up on loading time, History API will be appropriate - so do the frameworks listed above.
  • Link + click - at your discretion :)
    for target="_blank" attribute a good browser will block the operation. Without an attribute a lot of most popular pages will manage it like google ;)

 

What do you think about proposed redirection approaches?
Do you have any idea how to make a redirection another way?

Please write it in the comments - I will be happy to exchange experience.

 

Once again, I invite you to the technical version of the article here.
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Blog posts

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join