如何使用js重定向访问者

How to redirect visitor using js

本文关键字:访问者 重定向 js 何使用      更新时间:2023-09-26

当用户第一次访问1号页面时,如何使用javascript将1号html页面中的用户重定向到另一个2号html页面。如果可能的话,请帮我。

只需使用cookie标记用户第一次并使用document.location:重定向即可

if ( getCookie( 'first-time' ) === undefined ) {
    setCookie( 'first-time', 'yes' );
    document.location = '/second-page-url';
}

要使用cookie,请阅读此Set cookie并使用JavaScript获取cookie,以及此get-cookie by name

你需要在第一次访问时设置一个cookie,然后你可以检查用户以前在你的网站上。

要检查第一次访问是否可以使用cookie或localStorage
重定向有几种方法/机制:本文很好地解释了

同意legotin,但您需要以某种方式读取/写入cookie:

阅读cookie:

function getCookie(name) {
      var matches = document.cookie.match(new RegExp(
        "(?:^|; )" + name.replace(/(['.$?*|{}'(')'[']'''/'+^])/g, '''$1') + "=([^;]*)"));
      return matches ? decodeURIComponent(matches[1]) : undefined;
    }

设置cookie:

function setCookie(name, value, options) {
  options = options || {};
  var expires = options.expires;
  if (typeof expires == "number" && expires) {
    var d = new Date();
    d.setTime(d.getTime() + expires * 1000);
    expires = options.expires = d;
  }
  if (expires && expires.toUTCString) {
    options.expires = expires.toUTCString();
  }
  value = encodeURIComponent(value);
  var updatedCookie = name + "=" + value;
  for (var propName in options) {
    updatedCookie += "; " + propName;
    var propValue = options[propName];
    if (propValue !== true) {
      updatedCookie += "=" + propValue;
    }
  }
  document.cookie = updatedCookie;
}