在我的主页上,我有以下脚本,当用户访问我们的网站时,我们会检查两件事
-
如果屏幕尺寸小于 800,如果是这样,我们会将它们重定向到移动网站
如果他们来自移动网站, 因为他们可以选择从移动网站上的页脚"查看完整网站",那么我们需要创建一个cookie,以允许个人浏览网站而不会受到任何干扰。
现在使用下面的代码,我们遇到了一些问题。 当我们这样做时,如下所示
var value = getCookie('example');
值总是被低估,如果他们第一次直接浏览该网站并且以前的 url 不是移动网站,我会期望这一点。
但是,如果我直接转到主站点并被定向到移动设备并按"查看完整站点",则以下脚本将运行,但永远不会创建cookie,因此当我单击主站点上的菜单项之一并浏览回主页时,我被重定向到移动站点,因为cookie的值被低估了? 所以问题是我在做什么错了?
要澄清cookie是否为空,请将他们重定向到移动网站,如果不是空,请不要重定向,允许他们浏览主网站。
var oldURL = document.referrer;
var value = getCookie('example');
alert(oldURL);
alert(value); // Always undefined?
// If this is true they have come from the mobile site
if (oldURL.indexOf("m.domain") > -1) {
if (value == null) {
var date = new Date();
var minutes = 30;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie("example", "Yes", { expires: date });
}
}
else { // Otherwise if the screen width is small then 800px wide re-direct them to the mobile site
if (value == null) { // If value is null that means they have come to the main site so re-direct them to the mobile version
if (screen.width <= 800) {
window.location = "m.domain.com";
}
}
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^s+|s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
好的,设法让它与以下内容一起工作。
var oldURL = document.referrer;
var t = getCookie("fromMobile");
if (oldURL.indexOf("m.domain") > -1) {
var date = new Date();
var minutes = 30;
date.setTime(date.getTime() + (minutes * 60 * 1000));
document.cookie = "fromMobile=Yes; expires="+ date.toGMTString() +"; path=/";
} else {
if (t == "") {
if (screen.width <= 800) {
window.location = "http://m.domain.com";
}
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}