Javascript if else url redirect



What is Page Redirection ?

You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. This concept is different from JavaScript Page Refresh.

There could be various reasons why you would like to redirect a user from the original page. We are listing down a few of the reasons −

  • You did not like the name of your domain and you are moving to a new one. In such a scenario, you may want to direct all your visitors to the new site. Here you can maintain your old domain but put a single page with a page redirection such that all your old domain visitors can come to your new domain.

  • You have built-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server-side page redirection, you can use client-side page redirection to land your users on the appropriate page.

  • The Search Engines may have already indexed your pages. But while moving to another domain, you would not like to lose your visitors coming through search engines. So you can use client-side page redirection. But keep in mind this should not be done to fool the search engine, it could lead your site to get banned.

How Page Re-direction Works ?

The implementations of Page-Redirection are as follows.

Example 1

It is quite simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows.

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function Redirect() {
               window.location = "https://www.tutorialspoint.com";
            }
         //-->
      </script>
   </head>
   
   <body>
      <p>Click the following button, you will be redirected to home page.</p>
      
      <form>
         <input type = "button" value = "Redirect Me" onclick = "Redirect();" />
      </form>
      
   </body>
</html>

Output

Example 2

You can show an appropriate message to your site visitors before redirecting them to a new page. This would need a bit time delay to load a new page. The following example shows how to implement the same. Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval.

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function Redirect() {
               window.location = "https://www.tutorialspoint.com";
            }            
            document.write("You will be redirected to main page in 10 sec.");
            setTimeout('Redirect()', 10000);
         //-->
      </script>
   </head>
   
   <body>
   </body>
</html>

Output

You will be redirected to tutorialspoint.com main page in 10 seconds!

Example 3

The following example shows how to redirect your site visitors onto a different page based on their browsers.

<html>
   <head>     
      <script type = "text/javascript">
         <!--
            var browsername = navigator.appName;
            if( browsername == "Netscape" ) {
               window.location = "http://www.location.com/ns.htm";
            } else if ( browsername =="Microsoft Internet Explorer") {
               window.location = "http://www.location.com/ie.htm";
            } else {
               window.location = "http://www.location.com/other.htm";
            }
         //-->
      </script>      
   </head>
   
   <body>
   </body>
</html>

If you’re building or maintaining a website, chances are, at some point you’re going to need to redirect your users to a new address. For example, you might have moved to a new domain, bought a second one, or moved an existing page to a different part of your site.

In some cases, this is accomplished at the server level, with HTTP redirects via .htaccess or Nginx. 

Server side redirects have the advantage of using HTTP 3xx status codes. These status codes tell the user agent (such as search engine crawlers) why the redirect was set up, which can be helpful for SEO. For example, an HTTP 301 redirection indicates that the page in question was moved permanently to a new location.

By contrast, JavaScript redirects are client side, meaning that they tell the browser to retrieve content from a different location. You might want to use a client side redirect like JavaScript if:

  • You don’t have access to your server configuration or .htaccess file
  • You want to tie the redirect to a specified event or user action
  • You’re running an A/B test
  • You need additional checks or validation before redirecting
  • You have other needs that can’t easily be handled using an HTTP redirect

Below are three of the most common ways to create a redirect link in JavaScript using the location object, which is an entity that contains information about the current URL.

Set a New window.location.href Property

The simplest and most common way to use JavaScript to redirect to a URL is to set the location property to a new URL using window.location.href.

The JavaScript code looks like this:

window.location.href = ‘https://ExampleURL.com/’;

On its own, window.location.href is a property that tells you what URL is currently being viewed. By setting a new value (an equal sign, followed by your new target URL in single quotes), you are telling the browser to load that new URL, similar to what would happen if a user clicked a link. 

Using “window.location.href” to redirect adds a new entry to the current session history, meaning if the user clicks their “back” button, they can still return to the originating page. 

This method tends to be a little faster than calling a function, which is what happens in the other two methods described below. However, speed can vary depending on the browser you’re using to test. It also tends to be supported by more browsers, compared to other methods. (A “function” is a block of code in JavaScript that completes a designated task. Typically, this task involves taking an input, and returning an output.)

Pro Tip: If you’re using the “window.location.href” method, make sure you don’t set up the redirect to run automatically, or the user will get stuck in a redirect loop whenever they try to go back to the previous page. Instead, consider tying it to a user action. If you don’t want them to be able to go back, consider using the “window.location.replace” function instead.

Redirect Using the location.assign() Method

From a user’s perspective, a redirect using “window.location.assign()” looks the same as setting a new href property, as in the previous example. This is because: 

  • They both create a new entry in your session history (similar to clicking on a link)
  • They both enable users to go back and view the previous page

Here is what it looks like:

window.location.assign(‘https://www.ExampleURL.com/’);

Despite the similarities, “location.assign()” is different from “location.href” in a few important ways. 

Location.assign() calls a function to display the document located at the specified URL. Depending on your browser, this can be slower than simply setting a new href property. 

It can also be considered a safer option than setting a new href property, because if the target link is broken or is not secure, the function will throw a DOMException. In JavaScript, a DOMException is an error message that can occur when calling a function or accessing a property.

Pro Tip: If you need to redirect to a separate domain using location.assign(), you must use HTTPS. If you do not, your redirect will not work, and will instead throw an exception for a security error.

Redirect Using the location.replace() Method

Like “location.assign(),” “window.location.replace()” calls a function to display a new document located at the specified URL. 

It looks like this:

window.location.replace(‘https://www.ExampleURL.com/’);

Unlike setting a new location property or using “location.assign(),” the replace method does not create a new entry in your session history. Instead, it replaces the current entry — meaning users cannot click the back button and return to the previous, pre-redirect page. As such, this method is ideal if you want to use JavaScript to prevent users from viewing the page you’re directing them away from. 

This method has similar strengths and weaknesses as location.assign(), in that it:

  • Doesn’t allow you to redirect to unsecure or broken links, and will instead throw a DOMException when you try to use one
  • May be slower than setting a new window.location.href property
  • Requires HTTPS if you want to redirect to a new domain

Pro Tip: Unlike HTTP redirects, JavaScript does not tell crawlers why the redirect was put into place. As such, if your page was moved permanently, you may want to consider a redirect using .htaccess or your server configuration, if possible. 

Use Site Audit to Identify Redirect Issues

If you're implementing redirects on your site in any way, it's best to routinely audit your site with a tool like Site Audit. While Site Audit is unable to render JavaScript, it can identify a variety of redirect-related checks, including:

  • Redirect chains and loops
  • Missing redirect or canonical to HTTPS homepage from HTTP version
  • Temporary or permanent redirects (which are not necessarily an issue if used properly)

Redirects of any kind can be useful for your site, but it’s important to implement them properly in order to avoid technical SEO issues.

If you're just starting out or want to practice JavaScript, you can visit a website like W3Schools, which offers an interactive "TryIt Editor" for JavaScript, HTML, CSS, and more:

Javascript if else url redirect

Final Thoughts: Always Check Your Work

Used effectively, redirects (JavaScript and otherwise) can have a major impact on the user experience on your website, guiding users to the most relevant content for their needs. 

However, developing and maintaining a website is a complicated process, and mistakes can be costly. 

If you want your users to have the best possible experience, it’s crucial that you check your work rigorously. Site Audit can make this process easier by automating your site checks, identifying the most critical issues impacting your site’s performance and user experience, and providing tips on how to fix them.

How can you redirect the browser to a new URL from JavaScript?

Summary.
To redirect to a new URL or page, you assign the new URL to the location. href property or use the location. assign() method..
The location. replace() method does redirect to a new URL but does not create an entry in the history stack of the browser..

How do I redirect to another website?

How to Redirect to Another Page in HTML. To redirect one HTML page to another page, you need to add a <meta> tag inside the <head> section of the old HTML page. The <head> section of an HTML document contains metadata that is useful for the browser, but invisible to users viewing the page.

How do you redirect the current page to a new URL say Google com'in JavaScript?

jQuery code to redirect a page or URL.
var url = "http://stackoverflow.com"; $(location). attr('href',url); Run code snippet. ... .
// Doesn't put originating page in history window. location. replace("http://stackoverflow.com"); ... .
var url = "http://stackoverflow.com"; $(location). prop('href', url); Run code snippet..

Can you redirect a URL to a specific page?

Click the URL Redirects tab. In the upper right, click Add URL redirect. In the right panel, select the Standard or Flexible redirect type. A standard redirect is used to redirect one URL to another.