我有一个网页(home.html),我希望一次只能访问一次。
也就是说,一个人可以在他/她第一次打开时进入该页面。但是当此页面在选项卡中查看时,如果此人尝试在新选项卡中打开home.html,则会打开另一个页面。
我该怎么做?我需要在我的网页中添加哪个JS功能?
答案 0 :(得分:2)
本地存储,并在主体加载/卸载事件上触发:
function session1() {
var result = localStorage.getItem("session");
if (result != "running") {
localStorage.setItem("session", "running");
} else if (result == "running") {
localStorage.setItem("redirect", "yes");
window.location.replace("http://www.google.com");
}
}
function session0() {
var stats = localStorage.getItem("redirect");
if (stats == "yes") {
} else {
localStorage.setItem("session", "done");
}
localStorage.setItem("redirect", "no");
}

<body onload="session1()" onunload="session0()">
<div style="background:skyblue">SESSION RUNNING</div>
&#13;
答案 1 :(得分:0)
您可以尝试使用localStorage和onbeforeunload事件,这可能是:
if(localStorage['visited'] == true){
document.getElementsByTagName('body')[0].innerHTML = 'This page is opened twice.';
}
localStorage['visited'] = true;
window.onbeforeunload = function(){
localStorage['visited'] = false;
}