首页 > 解决方案 > 如何使用 cookie 进行重定向

问题描述

我想在同一个站点上进行两种类型的域重定向(if else 语句等):

If user has cookie:
And url subdomain is amazon then redirect to url xxxxxx
And url subdomain is ebay then redirect to url xxxx

If user has no cookie:
And url subdomain amazon then first forward to ebay subdomain and back to amazon subdomain once (currently creates a loop) and display background xxxx with href link xxxx
And url subdomain ebay then first forward to amazon subdomain and back to ebay subdomain once (currently creates a loop) and display background xxxx with href link xxxx

同步用户跨域单击以获取 href xxxxx 的新弹出窗口 - 即,如果用户通过单击另一个站点上的链接进入站点,则查看异步单击以打开另一个弹出窗口(200 秒规则)

当前站点已经具有我仍然需要的以下内容,因此由于下面的代码,cookie重定向不应设置到外部站点的重定向,但前提是用户确实是返回用户

var subdomain = window.location.hostname.split('.')[0];
if (!document.cookie == null && subdomain === "amazon") {
  window.location = "http://www..com";
} else if (!document.cookie == null && subdomain === "ebay") {
  window.location = "http://www.tutorialspoint.com";
} else if (document.cookie == null && subdomain === "amazon") {
  var oLinksArray = [];
  oLinksArray[0] = 'http://www.ebay.com';
  oLinksArray[1] = 'http://www.amazon.com';
  for (var x = 0; x < 2; x++) {
    var openWindow = window.open(oLinksArray[x]);
    setTimeout(function() {
      openWindow.close();
    }, 2000);
  }
} else if (document.cookie == null && subdomain === "ebay") {
  var oLinksArray = [];
  oLinksArray[0] = 'http://www.amazon.com';
  oLinksArray[1] = 'http://www.ebay.com';
  for (var x = 0; x < 2; x++) {
    var openWindow = window.open(oLinksArray[x]);
    setTimeout(function() {
      openWindow.close();
    }, 2000);
  }

} else {}

标签: javascriptcookies

解决方案


您不需要通过重定向传输 cookie。Cookie有一个名为 的属性domain。您应该添加网站的域以授予它们访问权限。

在 Javascript 中

var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate 
                  + ";domain=firstDomain.com,nextDomain.com;path=/";

在 PHP 中

setcookie('mycookie','mydata1',time() + 2*7*24*60*60,'/','www.firstDomain.com,nextDomain.com', false);

推荐阅读