重定向到其他页面仅使用Cookie一次



目的是通过重定向到警告页面来提醒用户,但只能重定向一次。

<script type="text/javascript">
var location = "https://mysitedotcom";
var alerted = localStorage.getItem('alerted') || '';
if (alerted != 'yes') {
localStorage.setItem('alerted','yes');
window.location.replace(location);
</script>

然而,我似乎得到了一个无限循环重定向到网站的索引。有什么东西我错过了吗>

虽然您缺少if的右大括号,但我认为您只是在粘贴代码时错过了它。问题是,你在全局范围内用var声明location,但已经有了一个,浏览器的本地location变量,其中包含位置信息,如果你将其分配给一个url字符串,它将重定向到该url。因此,您唯一需要做的就是更改变量名,其余代码应该可以正常工作:

<script type="text/javascript">
var newLocation = "https://mysitedotcom";
var alerted = localStorage.getItem('alerted') || '';
if (alerted != 'yes') {
localStorage.setItem('alerted','yes');
window.location.replace(newLocation);
}
</script>

最新更新