我试图在关闭选项卡的时候添加一个函数,弹出并显示“休假”和“取消”,我想为特定按钮添加一个函数,例如,如果我单击“离开”按钮,它应该调用一个函数,如果我单击“取消”按钮,则应该调用其他函数。请提前帮我谢谢
window.addEventListener("beforeunload", (ev) => {
ev.preventDefault();
socket.current.emit(
"logout_patient",
history.location.state.data.doctorAlias,
socket.current.id,
history.location.state.data.patientId
);
return ev.returnValue = 'Are you sure you want to close?';
});
发布于 2021-12-28 11:03:25
使用一个event('beforeunload').无法实现此功能
您可以使用窗口unload
事件来检查用户对弹出窗口左边的单击。
window.requestAnimationFrame
以检查您单击“取消”。
参考文献:https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event
const onCancel = () => {
console.log("I am the 2nd one.");
};
const onLeave = () => {
console.log("I am the 3rd one.");
// This loop is just to make sure that the event is fired
for (var i = 0; i < 100000; i++) {
console.log(event.returnValue);
}
};
const onExit = (e) => {
if (!e) e = window.event;
e.returnValue = "You sure you want to leave?";
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
console.log("I am the 1st one.");
window.requestAnimationFrame(onCancel);
};
window.addEventListener("beforeunload", onExit, { capture: true });
window.addEventListener("unload", onLeave);
https://stackoverflow.com/questions/70422559
复制相似问题