Header location javascript redirect

How to Redirect to Another Web Page Using JavaScript?

In this article we’ll look at different ways we can use to redirect to a new web page (or a resource) using only JavaScript. In addition to that we’ll also be exploring the potential fallbacks you can put in place when JavaScript is disabled, the SEO impact of using JavaScript for redirection purposes and alternative solutions.

Redirect Using JavaScript

Ideally, a redirect should be issued from the backend with correct HTTP redirect headers sent to the client. But if we must redirect from JavaScript, we can do so using the methods below:

// redirect to a new page window.location.href = 'https://www.example.com/'; // same as window.location.href = . window.location = 'https://www.example.com/'; window.location.assign('https://www.example.com/'); // redirect to new page and, // replace the original document in browser history with new one window.location.replace('https://www.example.com/');

In most cases, the replace() function might be the best option as it won’t cause redirect loops when users hit the browser’s back button.

Some browsers and most web crawlers may not execute JavaScript for various reasons, which is why having a fallback in place is a good idea.

Fallback When/If JavaScript Is Disabled:

Preferably, we should issue HTTP headers originating from the backend (server-side) to issue a redirect with appropriate redirection code. However, since we’re specifically talking about JavaScript / Frontend redirection, we could use HTML’s meta tag refresh (in the section of the web page) to instruct the browser to refresh the current web page (or an iframe ) after a specified time interval (in seconds). Consider the following example:

Читайте также:  Print exception type python

The 0 specified in the content attribute instructs the browser to redirect immediately. Changing it to a positive non-zero value would instruct the browser to wait before refreshing the page (the value is interpreted in seconds).

Additionally, we can place a fallback, for example a link, for older browsers in case the meta refresh doesn’t work:

To make sure, the code only executes when/if the browser has JavaScript disabled, we could wrap the meta tag (or other relevant code) inside a noscript tag like so:

Potential Side-Effects:

  • If a page redirects too quickly (i.e. in less than 2-3 seconds), it can break the Back button on the browser as each time you move back to the redirecting page, redirection will occur again almost immediately. This is especially bad in terms of usability as it can trap the user on the page he was redirected to.
  • It can be considered as a «Doorway Page» which is considered as an un-ethical SEO process by search engines.
  • Sometimes a mistake, or poorly planned redirections, can cause an infinite sequence of redirects, redirecting back and forth between two or more pages.

JavaScript Redirect’s Impact on SEO:

Why a JavaScript Redirect May Impact Your Search Engine Ranking Negatively:

Like mentioned previously, most web crawlers may not execute JavaScript which may negatively impact your web page’s search engine ranking. You might imagine using meta refresh would resolve the issue for all web crawlers, but such is not the case. In fact, an HTML page that contains a meta refresh element returns an HTTP status code of 200 OK (which is different from redirect status codes such as 301, 302, etc.). How that HTML 200 OK response (with a meta refresh tag) is processed and/or interpreted by a user-agent/bot/crawler depends entirely on the agent, its specific purpose and its programming.

Alternatives to JavaScript Redirect, Without Compromising SEO:

The best way to overcome these issues may be:

  1. To add a link rel=canonical in the section of your web page to inform search engines of a duplicate page (e.g. ); this is easier to implement as it doesn’t involve doing anything on the server-side. However, you must keep in mind that all search engines or web crawlers may not honor it;
  2. To issue either of the following HTTP headers from the web server (or a backend/server-side script):
    1. To properly issue an HTTP redirect header with most-appropriate redirect status code such as 301, 302, etc., or;
    2. To display a 404 Not Found for web pages that you may want to kill off and let die.

    Although a 404 may be considered bad for SEO in most cases, it may still be more meaningful in some. To help determine what course of action may be best suited in your particular case, you might want to ask yourself the following:

    1. Does the page receive important links to it from external sources?
    2. Does the page receive a considerable amount of visitor traffic?
    3. Is it an obvious (or a popular) URL that visitors/links intended to reach?

    If answer to any of those is a yes, you might want to consider a 3xx redirect instead of a 404 . Otherwise, it may be alright to issue a 404 – the reason being 1) we’d save up bandwidth from search engines trying to crawl and index a junk/stale page, and 2) we’d be able to inform the user about the error and display a search option and/or other relevant links instead (which may enhance the user experience).

    Redirect Immediately After Page Load

    By simply placing the redirect code in the section of the webpage (wrapped in script tag of course) we can issue an immediate redirect. For example:

    window.location.href = "https://www.example.com";

    Or, as an alternative, we could also use an inline onload event on the body tag like so:

    In this case, however, you must note that everything that preceedes the body tag will be parsed by the browser first.

    Redirect When Web Page Loads:

    If you wish to make sure the web page finishes loading, or certain scripts etc. load before issuing a redirect, depending on exactly when you intend to do it, you may benefit from the following three events in this particular case:

    1. window.onload Event: fired when DOM is ready and all the contents including images, css, scripts, sub-frames, etc. finished loaded (i.e. everything is loaded).
    2. document.onload Event: fired when DOM tree (built from markup code within the document ) is ready, which can be prior to images and other external content is loaded.
    3. document.onreadystatechange Event: fired when:
      1. the document is still loading;
      2. document finished loading with resources (such as images, css, frames, etc.) still pending;
      3. document and all sub-resources have finished loading (i.e. window.onload is about to fire).

      Examples:

      // Example #1 window.addEventListener('load', function(event) < // all resources finished loading window.location = 'https://www.example.com/'; >);
      // Example #2 document.onreadystatechange = function () < switch(document.readyState) < case 'loading': // document still loading break; case 'interactive': // document has finished loading; DOM elements can now be accessed break; case 'complete': // page is fully loaded (i.e. all resources finished loading) break; >>

      Redirect After a Certain Period of Time Has Elapsed

      To delay the redirect by a few seconds, we can use JavaScript’s setTimeout function like so:

      // redirect in 3 seconds (or 3000 ms) setTimeout(function() < window.location.href = "https://www.example.com"; >, 3000);
      • Time in setTimeout function is defined in miliseconds (i.e. 1000 ms = 1 second).
      • Since a web page is parsed sequentially from top to bottom, script tags (that are not marked defer or async ) load and execute before the parsing of the rest of the page continues. Therefore, placing the code in the section of the web page should execute the code immediately and redirect in the specified number of miliseconds. You could, however, also place this code at the end of the web page (or anywhere in the page for that matter), which would mean the code will execute when the browser parser reaches the particular segment of the code in the document.

      Hope you found this post useful. It was published 22 Mar, 2017 (and was last revised 01 Jun, 2020 ). Please show your love and support by sharing this post.

      Источник

      Редирект на JavaScript

      Редирект на JavaScript

      Редирект — это автоматическое перенаправление пользователя с одного адреса на другой. То есть человек заходит на один сайт, а оказывается совсем на другом (либо на другой странице одного сайта). Я, думаю, что такое Вы видели достаточно часто. Иногда редирект делают с задержкой. В общем, тема очень важная, и её я рассмотрю в этой статье.

      Вообще говоря, речь пойдёт сейчас об объекте Location, который является свойством объекта Document. У объекта Location есть свойство href, с помощью которого и реализуется редирект на JavaScript. Данное свойство доступно и для чтения, и для записи. Для начала давайте его прочитаем:

      В результате Вы увидите полный адрес к Вашему скрипту.

      Теперь сделаем простейший редирект на JavaScript:

      Таким образом, все пользователи, которые запустят этот скрипт будут автоматически переходить на сайт: «http://myrusakov.ru«.

      Теперь давайте сделаем классическую задачу, которые реализуют очень часто. Допустим, у Вас был сайт: http://a.ru. Затем Вы купили новый домен для Вашего сайта и его адрес стал: http://b.ru. И хотите, чтобы все посетители переходили с http://a.ru на новый http://b.ru. Причём, Вы хотите, чтобы они знали, что у Вашего сайта новый адрес. Знакома ситуация? Так вот, реализуется это с помощью редиректа с задержкой:

      Сначала пользователь увидит сообщение, а через 5 секунд он уже перейдёт по новому адресу. Если вдруг у пользователя отключён JavaScript, то тогда он может перейти самостоятельно, просто щёлкнув по ссылке.

      Как видите, сложное слово редирект оказалось очень простым не только в понимании, но и в использовании. И реализация редиректа в JavaScript очень и очень простая.

      Создано 18.10.2010 10:37:00

    4. Михаил Русаков
    5. Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

      Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
      Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

      Если Вы не хотите пропустить новые материалы на сайте,
      то Вы можете подписаться на обновления: Подписаться на обновления

      Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

      Порекомендуйте эту статью друзьям:

      Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

      1. Кнопка:
        Она выглядит вот так:
      2. Текстовая ссылка:
        Она выглядит вот так: Как создать свой сайт
      3. BB-код ссылки для форумов (например, можете поставить её в подписи):

      Комментарии ( 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-2023 Русаков Михаил Юрьевич. Все права защищены.

      Источник

Оцените статью