Redirect page from javascript

How to redirect to another web page using JavaScript

JavaScript offers many ways to redirect the user to a different web page, if during the execution of your program you need to move to a different page.

The one that can be considered canonical to navigate to a new URL is

window.location = 'https://newurl.com'

If you want to redirect to a different path, on the same domain, use:

window.location.pathname = '/new'

This is using the location object offered by the History API.

Other options to redirect

As with most things in programming, there are many ways to perform the same operation.

Since window is implicit in the browser, you can also do:

Another way is to set the href property of location :

window.location.href = 'https://newurl.com'

location also has an assign() method that accepts a URL, and performs the same thing:

window.location.assign('https://newurl.com')

The replace() method is different than the previous ways because it rewrites the current page in the history. The current page is wiped, so when you click the “back” button, you go back to the page that now is the last visited one.

window.location.replace('https://newurl.com')

This can be convenient in some situations.

Different ways to reach the window object

The browser exposes the self and top objects, which all reference the window object, so you can use them instead of window in all the examples above:

self.location = 'https://newurl.com' top.location = 'https://newurl.com'

301 redirect using a server-side directive

The above examples all consider the case of a programmatic decision to move away to a different page.

If you need to redirect because the current URL is old, and move the a new URL, it’s best to use server-level directive and set the 301 HTTP code to signal search engines that the current URL has permanently moved to the new resource.

This can be done via .htaccess if using Apache. Netlify does this through a _redirects file.

Are 301 redirects possible using JavaScript?

That’s not possible to do on the client-side.

The 301 HTTP response code must be sent from the server, well before the JavaScript is executed by the browser.

Experiments say that JavaScript redirects are interpreted by the search engines like 301 redirects. See this Search Engine Land post for reference.

Using JavaScript to redirect users can be a legitimate practice. For example, if you redirect users to an internal page once they’re logged in, you can use JavaScript to do so. When examining JavaScript or other redirect methods to ensure your site adheres to our guidelines, consider the intent. Keep in mind that 301 redirects are best when moving your site, but you could use a JavaScript redirect for this purpose if you don’t have access to your website’s server.

Use an HTML meta tag

Another option is using a meta tag in your HTML:

html>  head>  meta http-equiv="refresh" content="0;URL=https://newurl.com/">  head> html>

This will cause the browser to load the new page once it has loaded and interpreted the current one, and not signal search engines anything. The best option is always to use a 301 server-level redirect.

Источник

JavaScript Redirect

Summary: in this tutorial, you will learn how to use JavaScript to redirect to a new URL or page.

Introduction to the JavaScript redirect

Sometimes, you want to redirect users from one page to another page that has a different URL.

For example, you can create an app landing page that purely redirects the users to the Google Play or Apple Store, depending on the operating system that their smartphones have.

  • Detect the operating system of the smartphones
  • Redirect to Apple Store if the OS is iOS and Google Play if the OS is Android.

The redirection can be done in the web browsers using JavaScript redirection API.

It’s important to note that JavaScript redirection runs entirely on web browsers. Therefore it doesn’t return the status code 301 (move permanently) like a server redirection.

Therefore, if you move the site to a separate domain or create a new URL for an old page, you should always use the server redirection.

Redirect to a new URL

To redirect web browsers to a new URL from the current page to a new one, you use the location object:

location.href = 'new_url';Code language: JavaScript (javascript)
location.href = 'https://www.javascripttutorial.net/';Code language: JavaScript (javascript)

Assigning a value to the href property of the location object has the same effect as calling the assign() method of the location object:

location.assign('https://www.javascripttutorial.net/');Code language: JavaScript (javascript)

Either of these calls will redirect to the new URL and create an entry in the history stack of the browser. It means that you can go back to the previous page via the Back button of the browser.

To redirect to a new URL without creating a new entry in the history stack of the browser, you use the replace() method of the location object:

location.replace('https://www.javascripttutorial.net/');Code language: JavaScript (javascript)

The following example creates a page that redirects web browsers to Google Play or Apple Store if the OS is Android or iOS. Otherwise, it’ll show a message indicating that the OS is not supported:

index.html

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Redirect title> head> body> div class="message"> div> script src="js/app.js"> script> body> html>Code language: HTML, XML (xml)

js/app.js

const apps = < Android: 'https://play.google.com/', iOS: 'https://www.apple.com/store', >; const platform = () => < let userAgent = navigator.userAgent || navigator.vendor || window.opera; if (/windows phone/i.test(userAgent)) return 'Windows Phone'; if (/android/i.test(userAgent)) return 'Android'; if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) return 'iOS'; return null; >; const redirect = () => < let os = platform(); if (os in apps) < location.replace(apps[os]); >else < const message = document.querySelector('.message'); message.innerText = 'Your OS is not supported'; > >; redirect();Code language: JavaScript (javascript)

First, define an apps object with the keys are OS and values are URLs of the Google Play and Apple Store:

const apps = < Android: 'https://play.google.com/', iOS: 'https://www.apple.com/store', >;Code language: JavaScript (javascript)

Second, define a function that detects the OS:

const platform = () => < let userAgent = navigator.userAgent || navigator.vendor || window.opera; if (/windows phone/i.test(userAgent)) return 'Windows Phone'; if (/android/i.test(userAgent)) return 'Android'; if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) return 'iOS'; return null; >;Code language: JavaScript (javascript)

Third, create the redirect() function that detects the OS and redirects the web browser based on the detected OS:

const redirect = () => < let os = platform(); if (os in apps) < location.replace(apps[os]); >else < const message = document.querySelector('.message'); message.innerText = 'Your OS is not supported'; > >;Code language: JavaScript (javascript)

Finally, call the redirect() function:

Redirect to a relative URL

The following script redirects to the about.html which is on the same level as the current page.

location.href = 'about.html';Code language: JavaScript (javascript)

The following script redirects to contact.html page located in the root folder:

location.href = '/contact.html';Code language: JavaScript (javascript)

Redirect upon page loading

If you want to redirect to a new page upon loading, you use the following code:

window.onload = function( ) < location.href = "https://www.javascripttutorial.net/"; >Code language: JavaScript (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 to redirect to another web page using JavaScript

Using JavaScript, you can run some code immediately upon page load that will send a user to another page (i.e. redirect the user).

Table of contents

Redirecting

For immediate directing, it is best to use the following code:

window.location.replace('https://example.com');

This fully replaces the URL from which the code is run in the browser history.

The advantage of this is that if a user goes back in their browser after the redirect, they will reach the page they were browsing before the redirect.

If you use window.location.href(‘https://example.com’) , it will also redirect the user. But if a user wants to then go back in the browser, they will access the redirecting page, and this will immediately redirect the user again.

Creating a redirection countdown

You’ve probably seen countdowns before being redirected on web pages before.

To create your own, create your redirect text, adding empty elements for both the redirect URL and countdown value within this text.

Then, select these elements in JavaScript.

In your script, you are going to want to create a recurring update to the countdown value using setInterval() and a delayed redirect using setTimeout() . The delay should be the countdown value multiplied by 1000 milliseconds.

Redirecting you to in

Summary

By accessing location.replace() on the global window object and passing in a URL, you can redirect a user to another page without the redirect page being saved in the user’s browser history.

Источник

Читайте также:  Can there be if without else in java
Оцените статью