询问用户是否确定要离开该站点(XHTML/JavaScript)

caw*_*caw 0 html javascript xhtml confirm

当用户离开我的网站的一个页面时,应该有一条警告消息,使用户可以选择留在页面上:

"你确定要关闭这个页面吗?"

下一页是内部页面还是外部页面并不重要.

我认为这可以使用onUnload事件处理程序完成,不是吗?

<body onunload="confirmClose()">
Run Code Online (Sandbox Code Playgroud)

然后,confirmClose()函数必须显示一个带有两个按钮的消息框,以便用户可以选择"Really leave"或"Stay".

function confirmClose() {
    return confirm('Really leave this page?')
}
Run Code Online (Sandbox Code Playgroud)

但是这个功能无法阻止卸载吧?

你有解决我的问题的方法吗?提前致谢!

Gab*_*ams 5

您只能提供文字.浏览器处理对话框(安全原因).以下是您可以使用的一些代码:

window.onbeforeunload = function (e) {
    var e = e || window.event;
    var msg = 'Are you sure you want to leave?';

    // For IE and Firefox
    if (e) {
        e.returnValue = msg;
    }

    // For Safari / chrome
    return msg;
}
Run Code Online (Sandbox Code Playgroud)

不过,请在不同的浏览器上试试这个.你会注意到消息的构造应该根据不同浏览器的对话框措辞而有所不同.

这是我使用的:

if (IsChrome) {
    return 'You were in the middle of editing. You will lose your changes if you leave this page';
} else {
    return 'You were in the middle of editing. Press OK to leave this page (you will lose your changes).';
}
Run Code Online (Sandbox Code Playgroud)