窗口模糊事件



>我试图阻止用户打开选项卡/窗口。我正在使用以下代码:

window.onblur = function() {
alert(
'Please do not switch the test window. You may be disqualified from the test'
);
};

它适用于窗口切换,但是当我尝试打开/切换选项卡时,它会无限循环反复显示警报框。

我知道原因。这是因为警报框本身触发了模糊事件,导致无限调用。我不想使用console.log,因为我想向用户传达警告。

我认为这是因为窗口在显示警报时失去了焦点,所以我认为这样的事情应该有效(代码未测试(:

var isBlurred = false;
window.onblur = function() {
if (!isBlurred) {
isBlurred = true;
alert('Please do not switch the test window. You may be disqualified from the test');
}
};
window.onfocus = function() {
isBlurred = false;
};

您可以使用标志来检查通知是否打开,也可以在重置该标志时使用小延迟。

var noticeIsOn = false;
window.addEventListener('blur', function() {
if (!noticeIsOn) {
noticeIsOn = true;

alert('Please do not switch the test window. You may be disqualified from the test');

setTimeout(function() {
noticeIsOn = false;
}, 100)
}
});

最新更新