You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cookie设置与读取跨浏览器兼容问题技术求助

Cookie跨浏览器兼容问题求助

我写了一段用来设置和读取Cookie的HTML代码,在Windows 10的FireFox里运行完全正常,但换到Chrome就彻底失效了。之后找了位用Mac的朋友帮忙测试,结果各种奇怪的情况都出现了,具体如下:

  • Chrome(Mac):关闭初始弹窗后重新加载页面,完全看不到任何和username相关的内容;输入“test”点击OK后,浏览器直接提示拦截了Cookie
  • Safari(Mac):首次加载会弹出提示框显示getCookie called withusername=一串以短横线分隔的4-5位十六进制数 helpSession=914438-1284431863267,关闭弹窗后才正常显示姓名输入框和右侧的“Cancel”“OK”按钮;输入“test”点击OK后会提示错误,但重新加载页面能看到getCookie called withusername=test; helpSession=914438-1284431863267;第三次点击OK后才终于正常显示“Welcome back test”

我把完整代码贴在下面,实在搞不懂哪里出了问题,为什么不同浏览器的表现差异这么大?有没有大佬能帮我分析下代码里的问题?

<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
alert( "expires=" + expires );
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
alert( "getCookie called" + document.cookie );
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
function checkCookie() {
var username = getCookie("username");
if (username != "") {
alert("Welcome back " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>

内容的提问来源于stack exchange,提问作者Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:51:38