Перенаправление на другую веб-страницу с помощью JavaScript/jQuery
В этом посте мы обсудим, как перенаправить на другую веб-страницу в JavaScript и jQuery.
Существует несколько способов перенаправления страницы в JavaScript, каждый из которых включает использование window.location имущество. Он возвращает Location объект, представляющий местоположение (URL) текущего документа.
1. Использование location.href
Когда вы назначаете URL для window.location.href связанный документ переходит на новую страницу из того же или другого источника.
С window является глобальным объектом, его можно сократить до:
Обратите внимание, что location является синонимом location.href . Таким образом, вы можете напрямую присвоить значение location объект.
2. Использование location.assign() функция
Вы также можете перейти к новому URL-адресу, используя location.assign() метод. Если указанный URL-адрес имеет другое происхождение, это может привести к сбою из-за политики CORS.
Обратите внимание, что assign() метод сохранит текущую страницу в истории сеанса, т.е. пользователь может вернуться назад с помощью кнопки «Назад».
3. Использование location.replace() функция
Существует еще один метод объекта местоположения, который называется replace() , который заменяет текущий документ документом по указанному URL-адресу. в отличие от assign() метод, это заменяет запись истории сеанса, и пользователь не может вернуться на исходную страницу с помощью кнопки «Назад».
3 Ways To Redirect On Click In Javascript (Simple Examples)
Welcome to a quick tutorial on how to redirect on click in Javascript. Need to redirect the user after they click on a button, or after they have submitted a form?
- <button onclick=»location.href=’URL'»> Redirect </button>
- <button onclick=»location.assign(‘URL’)»> Redirect </button>;
- <button onclick=»location.replace(‘URL’)»> Redirect </button>
Please enable JavaScript
While all these seem to do the same thing, they are actually slightly different. Read on for more examples and the differences!
ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TLDR – QUICK SLIDES
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
EXAMPLE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
ON CLICK REDIRECTION
All right, let us now get into more examples of how to do a webpage redirection in Javascript.
1) LOCATION HREF & LOCATION ASSIGN
- location.href is a property . We can retrieve the current URL from location.href , and assign a new URL to change the current page – location.href = URL .
- location.assign() is a function . We call this function to change the current page – location.assign(URL) .
2) LOCATION REPLACE
- location.href and location.assign() – Both will record the current page into the navigation history before redirecting. For example, we do a location.assign(«PAGE-B.HTML») on PAGE-A.HTML . The user can hit “back” and go back to PAGE-A.HTML .
- location.replace() – Replaces the current URL. For example, we do a location.replace(«PAGE-B.HTML») on PAGE-A.HTML . In the navigation history, PAGE-A.HTML is replaced with PAGE-B.HTML .
Long story short –
- Use location.href and location.assign() if you allow the user to go back.
- Use location.replace() if you don’t want the user to go back.
3) REDIRECT IN THE SAME PAGE – SCROLL TO BOOKMARK
- Give the element an ID. For example, <p >Foo</p> .
- Point the anchor link to the bookmark. For example, <a href=»#target»>Go To Foo</a> .
In Javascript, we can access the bookmark portion of the URL with location.hash . But here’s the problem – If we just set location.hash = «BOOKMARK» , that will not trigger a “scroll to element”. This is why we need to manually do an ELEMENT.scrollIntoView() .
EXTRA BITS & LINKS
That’s all for this guide, and here is a small section on some extras and links that may be useful to you.
EXTRA) LOCATION OR WINDOW.LOCATION?
In some other tutorials, you will see people using window.location instead of location . Is there a difference? Apparently, the answer is no. location and window.location refers to the same thing. So go ahead and be a lazy code ninja. It is safe to use location and drop that windows part.
EXTRA) WINDOW.NAVIGATE!?
If you have been poking around the Internet, you may have also spotted some tutorials using window.navigate() to redirect the page. Take extra note that window.navigate() is an ancient Internet Exploder Explorer thing. It is not supported in most modern browsers – Don’t use this anymore.
LINKS & REFERENCES
-
– MDN – MDN – StackOverflow – Code Boxx
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
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
Help your team get the information they need to do their job — reduce burnout and help engineers grow and learn together.
Always free up to 50 teammates
Basic
Up to 250 teammates
Business
Enterprise

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
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 © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.6.8.43486
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
JavaScript – перенаправление страниц
Возможно, вы столкнулись с ситуацией, когда вы нажимали URL-адрес, чтобы перейти на страницу X, но внутренне вы были перенаправлены на другую страницу Y. Это происходит из-за перенаправления страницы . Эта концепция отличается от JavaScript Page Refresh .
Могут быть разные причины, по которым вы хотите перенаправить пользователя с исходной страницы. Мы перечисляем несколько причин —
Вам не понравилось название вашего домена, и вы переходите на новый. В таком случае вы можете направить всех своих посетителей на новый сайт. Здесь вы можете сохранить свой старый домен, но разместить одну страницу с перенаправлением страницы, чтобы все посетители вашего старого домена могли перейти на ваш новый домен.
Вы создали различные страницы на основе версий браузера или их имен или в разных странах, и вместо перенаправления страниц на стороне сервера вы можете использовать перенаправление страниц на стороне клиента, чтобы пользователи попадали на соответствующую страницу.
Поисковые системы, возможно, уже проиндексировали ваши страницы. Но при переходе на другой домен вы не хотели бы потерять посетителей, посещающих поисковые системы. Таким образом, вы можете использовать перенаправление страниц на стороне клиента. Но имейте в виду, что это не должно быть сделано, чтобы обмануть поисковую систему, это может привести к тому, что ваш сайт будет заблокирован.
Вам не понравилось название вашего домена, и вы переходите на новый. В таком случае вы можете направить всех своих посетителей на новый сайт. Здесь вы можете сохранить свой старый домен, но разместить одну страницу с перенаправлением страницы, чтобы все посетители вашего старого домена могли перейти на ваш новый домен.
Вы создали различные страницы на основе версий браузера или их имен или в разных странах, и вместо перенаправления страниц на стороне сервера вы можете использовать перенаправление страниц на стороне клиента, чтобы пользователи попадали на соответствующую страницу.
Поисковые системы, возможно, уже проиндексировали ваши страницы. Но при переходе на другой домен вы не хотели бы потерять посетителей, посещающих поисковые системы. Таким образом, вы можете использовать перенаправление страниц на стороне клиента. Но имейте в виду, что это не должно быть сделано, чтобы обмануть поисковую систему, это может привести к тому, что ваш сайт будет заблокирован.
Как работает перенаправление страницы?
Реализации перенаправления страницы следующие.
Пример 1
Это довольно просто сделать перенаправление страницы с помощью JavaScript на стороне клиента. Чтобы перенаправить посетителей вашего сайта на новую страницу, вам просто нужно добавить строку в ваш головной раздел следующим образом.
Выход
Пример 2
Вы можете показать соответствующее сообщение посетителям вашего сайта, прежде чем перенаправить их на новую страницу. Это потребует небольшой задержки для загрузки новой страницы. В следующем примере показано, как реализовать то же самое. Здесь setTimeout () — это встроенная функция JavaScript, которую можно использовать для выполнения другой функции через заданный интервал времени.
Выход
Пример 3
В следующем примере показано, как перенаправить посетителей вашего сайта на другую страницу в зависимости от их браузера.