- How to redirect to another web page using JavaScript
- Other options to redirect
- Different ways to reach the window object
- 301 redirect using a server-side directive
- Are 301 redirects possible using JavaScript?
- Use an HTML meta tag
- Response: redirect() static method
- Syntax
- Parameters
- Return value
- Exceptions
- Examples
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Response redirect and javascript
- About
- About
- About
- Response: redirected property
- Value
- Examples
- Detecting redirects
- Disallowing redirects
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
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.
Response: redirect() static method
The redirect() static method of the Response interface returns a Response resulting in a redirect to the specified URL.
Note: This is mainly relevant to the ServiceWorker API. A controlling service worker could intercept a page’s request and redirect it as desired. This will actually lead to a real redirect if a service worker sends it upstream.
Syntax
.redirect(url) Response.redirect(url, status)
Parameters
The URL that the new response is to originate from.
An optional status code for the response (e.g., 302 .)
Return value
Exceptions
The specified status is not a redirect status.
The specified URL is invalid.
Examples
.redirect("https://www.example.com", 302);
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 12, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Response redirect and javascript
Для переадресации применяется метод redirect() :
В качестве параметра path передается путь, на который будет перенаправляться пользователь. Дополнительный параметр status задает статусный код переадресации. Если этот параметр не задан, тогда по умолчанию отправляется статусный код 302, который предполагает временную переадресацию.
С помощью данного метода можно выполнять переадресацию как по относительным путям, так и по абсолютным, в том числе на другие домены.
Переадресация по абсолютному пути:
const express = require("express"); const app = express(); app.use("/index",function (request, response) < response.redirect("https://metanit.com") >); app.listen(3000);
В данном случае при обращении по пути «/index» будет идти переадресация на сайт https://metanit.com.
Переадресация по оносительным путям также не очень сложна, но здесь важно учитывать, как именно определяется адрес для редиректа. Рассмотрим редирект относительно текущего пути, с которого производится редирект. Например:
const express = require("express"); const app = express(); app.use("/home",function (request, response) < response.redirect("about") >); app.use("/about", function (request, response) < response.send("About
"); >); app.listen(3000);
В данном случае будет идти перенаправление с ресурса «/home» на ресурс «/about», то есть, условно говоря, с http://localhost:3000/home на http://localhost:3000/about.
Теперь рассмотрим похожий пример:
const express = require("express"); const app = express(); app.use("/home/bar",function (request, response) < response.redirect("about") >); app.use("/home/about", function (request, response) < response.send("About
"); >); app.listen(3000);
Здесь с ресурса «/home/bar» также идет переадресация на ресурс «about», однако в реальности теперь это будет не http://localhost:3000/about, а http://localhost:3000/home/about. То есть мы как-бы поднимаемся на один уровень вверх — с «home/bar» на «home/» и затем к нему добавляется «about».
Если нам необходимо выполнить переадресацию не относительно текущего ресурса, а относительно корневого каталога приложения, то в начале адреса ставится слеш:
const express = require("express"); const app = express(); app.use("/home/bar",function (request, response) < response.redirect("/about") >); app.use("/about", function (request, response) < response.send("About
"); >); app.listen(3000);
Еще несколько примеров. Переадресация относительно текущего адреса на адрес на том же уровне:
app.use("/home/foo/bar",function (request, response) < response.redirect("./about") >);
Здесь идет переадресация с http://localhost:3000/home/foo/bar на http://localhost:3000/home/foo/about
Переадресация на адрес, который располагается уровнем выше:
app.use("/home/foo/bar",function (request, response) < response.redirect("../about") >);
Здесь идет переадресация с http://localhost:3000/home/foo/bar на http://localhost:3000/home/about
Переадресация на уровень выше:
app.use("/home/foo/bar",function (request, response) < response.redirect(".") >);
Здесь идет переадресация с http://localhost:3000/home/foo/bar на http://localhost:3000/home/foo
Переадресация на два уровня выше:
app.use("/home/foo/bar",function (request, response) < response.redirect("..") >);
Здесь идет переадресация с http://localhost:3000/home/foo/bar на http://localhost:3000/home
По умолчанию при редиректе передается статусный код 302, который указывает, что ресурс временно доступен по новому адресу. Но мы можем указать статусный код 301, чтобы сделать переадресацию постоянной:
response.redirect(301, "/about");
Response: redirected property
The read-only redirected property of the Response interface indicates whether or not the response is the result of a request you made which was redirected.
Note: Relying on redirected to filter out redirects makes it easy for a forged redirect to prevent your content from working as expected. Instead, you should do the filtering when you call fetch() . See the example Disallowing redirects, which shows this being done.
Value
A boolean value which is true if the response indicates that your request was redirected.
Examples
Detecting redirects
Checking to see if the response comes from a redirected request is as simple as checking this flag on the Response object. In the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation. Note, however, that this isn’t as safe as outright rejecting redirects if they’re unexpected, as described under Disallowing redirects below.
The url property returns the final URL after redirects.
fetch("awesome-picture.jpg") .then((response) => const elem = document.getElementById("warning-message-box"); elem.textContent = response.redirected ? "Unexpected redirect" : ""; // final url obtained after redirects console.log(response.url); return response.blob(); >) .then((imageBlob) => const imgObjectURL = URL.createObjectURL(imageBlob); document.getElementById("img-element-id").src = imgObjectURL; >);
Disallowing redirects
Because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to «error» in the init parameter when calling fetch() , like this:
fetch("awesome-picture.jpg", redirect: "error" >) .then((response) => response.blob()) .then((imageBlob) => const imgObjectURL = URL.createObjectURL(imageBlob); document.getElementById("img-element-id").src = imgObjectURL; >);
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.