How to Use JavaScript to Redirect a URL
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:
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.
Source link : Semrush.com