javascript redirect to url
Редирект на JavaScript
Вообще говоря, речь пойдёт сейчас об объекте Location, который является свойством объекта Document. У объекта Location есть свойство href, с помощью которого и реализуется редирект на JavaScript. Данное свойство доступно и для чтения, и для записи. Для начала давайте его прочитаем:
В результате Вы увидите полный адрес к Вашему скрипту.
Теперь сделаем простейший редирект на JavaScript:
Таким образом, все пользователи, которые запустят этот скрипт будут автоматически переходить на сайт: «http://myrusakov.ru«.
Теперь давайте сделаем классическую задачу, которые реализуют очень часто. Допустим, у Вас был сайт: http://a.ru. Затем Вы купили новый домен для Вашего сайта и его адрес стал: http://b.ru. И хотите, чтобы все посетители переходили с http://a.ru на новый http://b.ru. Причём, Вы хотите, чтобы они знали, что у Вашего сайта новый адрес. Знакома ситуация? Так вот, реализуется это с помощью редиректа с задержкой:
У нашего сайта новый адрес: http://b.ru. Через 5 секунд Вы будете перенаправлены на него. Если этого не происходит, то перейдите самостоятельно: http://b.ru
Сначала пользователь увидит сообщение, а через 5 секунд он уже перейдёт по новому адресу. Если вдруг у пользователя отключён JavaScript, то тогда он может перейти самостоятельно, просто щёлкнув по ссылке.
Как видите, сложное слово редирект оказалось очень простым не только в понимании, но и в использовании. И реализация редиректа в JavaScript очень и очень простая.
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Комментарии ( 10 ):
Подскажи пожалуйста! Умеет ли JavaScript выводить на странице СТРАНУ и РЕГИОН пользователя? Если да, то нужна ли для этого база данных? А как нащёт IP-адреса? Я вставил какую-то картинку со стороннего сайта (в виде щётчика) и она показывает IP. Как это работает? Спасибо.
На чистом JS определить IP невозможно. Только лишь, например, через Ajax, который будет связываться с PHP-скриптом, определяющим IP и возвращающим его. Именно так и работают JS-счётчики.
А почему вы не написали про window.location?
А как сделать штоб послє первово сайта кидало на второй а патом єщо й на трєтій
Поставить редиректы на всех этих сайтах.
Спасибо! Познавательно! Для автоматического перехода с одной страницы на другую, также можно использовать тег meta (пишется в контейнер head), например,
Михаил, в каких случаях рекомендуется делать редиректы через JavaScript, а в каких черех РНР? Ну, кроме примера, приведенного в этой статье.Есть разница во времени работы редиректа на РНР и на JavaScript?
При использовании средств PHP происходит работа через функцию header, т.е. путём перегрузки заголовков. Но всё дело в том, что этот header(‘Location: url’), нужно отправить до вывода любой информациии в браузер (это правило для любого заголовка). Так вот когда структура сайта такова, что подключается масса файлов или же огромный код PHP в перемешку с HTML, то вызов header ведёт к тому, что просто на просто редирект не пашет. и это хорошо если у вас 1 такой файл.. а если 100? поэтому проще написать JS функцию и инклудить (или реквайрить) её в нужные страницы. При этом всё будет работать и путаницы с хедерами не будет.
Всё это хорошо для частного случая. Но гораздо больший функционал всё-таки у спец скриптов типа Smart Redirector 3.0 Тиссена Сергея http://r.online-biznes.com/6
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2021 Русаков Михаил Юрьевич. Все права защищены.
Every developer has a
tab open to
Stack Overflow
A public platform building the definitive collection of coding questions & answers
A community-based space to find and contribute answers to technical challenges, and one of the most popular websites in the world.
A private collaboration & knowledge sharing SaaS platform for companies
A web-based platform to increase productivity, decrease cycle times, accelerate time to market, and protect institutional knowledge.
Thousands of organizations around the globe use Stack Overflow for Teams
Capture your company’s knowledge and context in a discoverable format to unblock your team
Increase productivity
If somebody somewhere has the right answer, suddenly you have it too. Collaborate better in a remote-first world.
Accelerate time to market
Shorten the time between initial idea and complete product. Take delays and misinformation out of the equation.
Protect institutional knowledge
People come and people go, but if you capture their contributions in one central place, that expertise sticks around.
Ensure your company stays on course
Here are just a few types of technologists that we help.
DevOps engineers
Shipping new products and features requires teamwork and coordination. Forget checklists and long docs no one ever reads.
Data scientists
Business decisions are better when backed by data. Give visibility to the data that support your strategies.
Software engineers
Help engineers be more efficient and streamline knowledge sharing using a tool they already love and trust.
Support teams
Level up your support by providing information to your customers using a natural interface: questions and answers.
Engineering leaders
Free knowledge sharing and collaboration platform
Always free up to 50 teammates
Basic
Centralized knowledge and collaboration platform for small and growing teams
Up to 250 teammates
Business
For small and medium sized businesses seeking advanced administrative tools
Enterprise
For medium to large businesses with additional security, configurability and content management needs
Integrates with and improves other tools
All plans come with integrations for ChatOps tools Slack & Microsoft Teams in order to cut down on pings, limit distractions and make the tools even more powerful. Business and Enterprise customers get access to Jira, GitHub & Okta integrations.
Robust read and write API
Single sign-on with AD or SAML
Your own customer success representative
99.5% uptime SLA and priority support
Stack Overflow for Teams has been a resource for our entire company. Not only for developers to solve problems, it’s also enabled our sales field to answer technical questions that help them close deals.
Engineers should help solve the hardest questions, the unknowns, where being familiar with how the product was built is essential. But we don’t want to keep answering solved problems over and over again. That’s where Stack Overflow for Teams really helps.
As we started to use [Stack Overflow for Teams] and saw how nice it was to have a repository of information, we started to see it spread to other teams. Our customer support team started using it, our people success team started using it, next thing we knew, we had [Slack] integrations all over the place.
What we love about Stack Overflow for Teams is that it’s a very dynamic tool…there’s just so many ways to use this as a liaison between different teams and different knowledge bases.
Additional products that reach and engage developers & technologists…
Reach the world’s largest audience of developers and technologists
Connecting communities with the specific technologies they use the most
Build your employer brand to attract tech talent
Programming & related technical career opportunities
Explore technical topics and other disciplines across 170+ Q&A communities
From Server Fault to Super User, much of the Stack Exchange network continues our mission to empower the world to develop technology through collective knowledge. Other sites on the Stack Exchange network further encourage knowledge sharing across topics such as cooking and medicine.
Build a private community to share technical or non-technical knowledge.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40232
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Every developer has a
tab open to
Stack Overflow
A public platform building the definitive collection of coding questions & answers
A community-based space to find and contribute answers to technical challenges, and one of the most popular websites in the world.
A private collaboration & knowledge sharing SaaS platform for companies
A web-based platform to increase productivity, decrease cycle times, accelerate time to market, and protect institutional knowledge.
Thousands of organizations around the globe use Stack Overflow for Teams
Capture your company’s knowledge and context in a discoverable format to unblock your team
Increase productivity
If somebody somewhere has the right answer, suddenly you have it too. Collaborate better in a remote-first world.
Accelerate time to market
Shorten the time between initial idea and complete product. Take delays and misinformation out of the equation.
Protect institutional knowledge
People come and people go, but if you capture their contributions in one central place, that expertise sticks around.
Ensure your company stays on course
Here are just a few types of technologists that we help.
DevOps engineers
Shipping new products and features requires teamwork and coordination. Forget checklists and long docs no one ever reads.
Data scientists
Business decisions are better when backed by data. Give visibility to the data that support your strategies.
Software engineers
Help engineers be more efficient and streamline knowledge sharing using a tool they already love and trust.
Support teams
Level up your support by providing information to your customers using a natural interface: questions and answers.
Engineering leaders
Free knowledge sharing and collaboration platform
Always free up to 50 teammates
Basic
Centralized knowledge and collaboration platform for small and growing teams
Up to 250 teammates
Business
For small and medium sized businesses seeking advanced administrative tools
Enterprise
For medium to large businesses with additional security, configurability and content management needs
Integrates with and improves other tools
All plans come with integrations for ChatOps tools Slack & Microsoft Teams in order to cut down on pings, limit distractions and make the tools even more powerful. Business and Enterprise customers get access to Jira, GitHub & Okta integrations.
Robust read and write API
Single sign-on with AD or SAML
Your own customer success representative
99.5% uptime SLA and priority support
Stack Overflow for Teams has been a resource for our entire company. Not only for developers to solve problems, it’s also enabled our sales field to answer technical questions that help them close deals.
Engineers should help solve the hardest questions, the unknowns, where being familiar with how the product was built is essential. But we don’t want to keep answering solved problems over and over again. That’s where Stack Overflow for Teams really helps.
As we started to use [Stack Overflow for Teams] and saw how nice it was to have a repository of information, we started to see it spread to other teams. Our customer support team started using it, our people success team started using it, next thing we knew, we had [Slack] integrations all over the place.
What we love about Stack Overflow for Teams is that it’s a very dynamic tool…there’s just so many ways to use this as a liaison between different teams and different knowledge bases.
Additional products that reach and engage developers & technologists…
Reach the world’s largest audience of developers and technologists
Connecting communities with the specific technologies they use the most
Build your employer brand to attract tech talent
Programming & related technical career opportunities
Explore technical topics and other disciplines across 170+ Q&A communities
From Server Fault to Super User, much of the Stack Exchange network continues our mission to empower the world to develop technology through collective knowledge. Other sites on the Stack Exchange network further encourage knowledge sharing across topics such as cooking and medicine.
Build a private community to share technical or non-technical knowledge.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40232
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Next.js Redirect from / to another page
I’m new in Next.js and I’m wondering how to redirect from start page ( / ) to /hello-nextjs for example. Once user loads a page and after that determine if path === / redirect to /hello-nextjs
In react-router we do something like:
11 Answers 11
Edit : Next.js >= 10
From Next.js 10 you can do server side redirects (see below for client side redirects) with a redirect key inside getServerSideProps or getStaticProps :
In next.js you can redirect after the page is loaded using Router ex :
If you want to prevent the flashing before the redirect you can use a simple trick :
I would say that in general is not a good/elegant approach to do client redirects when you can use next.config.js redirects or even better use conditional render of components.
I have create a simple repo with all the examples above here.
Caveat
First, you should asses whether you need client-side redirection (within React), server-side redirection (301 HTTP response) or server-side redirection + authentication (301 HTTP response but also having some logic to check authentication).
Server-side redirection are tempting, in particular when you want to «secure» private pages, but you should assess whether you really need them. Usually, you don’t. They induce unexpected complexity, like managing auth token and refresh token. Instead, you may want to add a gateway server, a reverse proxy or whatever upfront server to your architecture for instance to handle those kind of checks.
Keep in mind that Next.js are just React app, and using Next.js advanced features like SSR comes at a cost that should be justified in your context.
Next 9.4 answer
Hi, here is an example component working in all scenarios:
The answer is massive, so sorry if I somehow break SO rules, but I don’t want to paste a 180 lines piece of code. There is no easy pattern to handle redirection in Next, if you want to both support SSR and static export.
The following scenarios each need a specific pattern:
Next 9.5 update
As stated by @Arthur in the comments, 9.5 also include the possibilities to setup redirects in next.config.js. The limitations of this feature are not yet clear to me, but they seem to be global redirections, e.g. when you need to move a page or to allow access only during a limited period. So they are not meant to handle authentication for instance, because they don’t seem to have access to the request context. Again, to be confirmed.
Next 10 new doc update
This solution is specific to redirection depending on authentication.
You may also want to check the approach documented in this ticket based on how Vercel’s dashboard works (at the time of writing), that prevents flash of unauthenticated content
Next 10.2 header and cookies based rewrites update
Next 10.2 introduces Rewrites based on headers and cookies. That’s a great way to redirect server-side, based on the presence of an authentication cookie or header.
However, keep in mind that this is not a secure redirection. User can alter their request headers with a false token. You still need a gateway, a reverse proxy or an upfront server to actually check token validity and correctly set the headers.
Edit: note that the URL won’t change. A rewrite points an URL to an existing page of your application, without changing the URL => it allows you to have «virtual» URLs.
Old answer (works, but will have a messy static render)
Semi-official example
It handles both server side and client side. The fetch call is the one that actually get the auth token, you might want to encapsulate this into a separate function.
What I would advise instead
1. Redirect on server-side render (avoid flash during SSR)
This is the most common case. You want to redirect at this point to avoid the initial page flashing on first load.
2. Redirect in componentDidMount (useful when SSR is disabled, eg in static mode)
This is a fallback for client side rendering.
I could not avoid flashing the initial page in static mode add this point, because you can’t redirect during the static build, but it seems better than the usual approaches. I’ll try to edit as I make progress.
How to redirect to another page in node.js [duplicate]
I would also like to know, how to redirect a user on button click.
Let’s say I’m on display user page, where I display all of my users, then there is «add another used button». How do i do that? How do I redirect user to Register.js page after onclick?
6 Answers 6
You should return the line that redirects
Ok, I’ll try to help you using one my examples. First of all, you need to know I am using express for my application directory structure and for creating files like app.js in an automatically way. My login.html looks like:
The important thing here is action=»/login». This is the path I use in my index.js (for navigating between the views) which look like this:
This allows me to redirect to another page after a succesful login. There is a helpful tutorial you could check out for redirecting between pages:
To read a statement like let’s have a look at a simple profile.html which has the following structure:
To get the the attributes of the user variable, you have to initialize a user variable in your routing.js (called index.js in my case). This looks like
I am using mongoose for my object model:
Ask me anytime for further questions. Best regards, Nazar