如何使用js重定向访问者

时间:2015-11-17 09:19:22

标签: javascript html redirect

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

4 个答案:

答案 0 :(得分:1)

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

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

要使用Cookie,请阅读此Set cookie and get cookie with JavaScript和此Get cookie by name

答案 1 :(得分:0)

您需要在首次访问时设置Cookie,然后您可以检查用户之前是否在您的网站上。

答案 2 :(得分:0)

要检查第一次访问,可以使用cookie或localStorage。
要重定向,有几种方法/机制:this article explains it well

答案 3 :(得分:0)

同意 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;
}