2009-08-26 90 views
6

是否可以在浏览器中为onbeforeunload事件创建自定义确认框?我试了一下,但后来我得到了2个确认框(从我这里得到的只是返回确认...,然后是浏览器中的标准框)。onbeforeunload确认屏幕定制

目前我的代码看起来像:

var inputChanged = false; 

$(window).load(function() { 
    window.onbeforeunload = navigateAway; 
    $(':input').bind('change', function() { inputChanged = true; }); 
}); 

function navigateAway(){ 
    if(inputChanged){ 
     return 'Are you sure you want to navigate away?'; 
    } 
} 

我使用jQuery这一点。

回答

11
window.onbeforeunload = function (e) { 
    var message = "Your confirmation message goes here.", 
    e = e || window.event; 
    // For IE and Firefox 
    if (e) { 
    e.returnValue = message; 
    } 

    // For Safari 
    return message; 
}; 

请注意:大多数浏览器把这个消息后,一些其他的文字。您无法完全控制确认对话框的内容。

+0

它确实很遗憾,无法覆盖此屏幕。 – 2009-08-27 07:28:45

3

不,你无法从浏览器中避免使用标准的。你所能做的只是向它注入一些自定义文本;如果你使用下面的事件处理(注册原型LIB方式):

Event.observe(window, "beforeunload", function(event) { 
    if (showMyBeforeUnloadConfirmation) 
     event.returnValue = "foo bar baz"; 
}); 

(和showMyBeforeUnloadConfirmation是真实的),你会得到浏览器的标准确认有以下文字:

确定你想离开这个页面吗?

富酒吧巴兹

按确定继续,或取消留在当前页面。

[确定] [取消]

0

我面临同样的问题,我能得到自己的对话框,我的消息,但我面临的问题是:

  1. 这对所有的导航给人的消息,我想它仅适用于紧密单击。
  2. 如果用户选择“取消”,用我自己的确认信息,它仍然显示浏览器的默认对话框。

以下是我找到的解决方案代码,这是我在母版页上写的。

function closeMe(evt) { 
    if (typeof evt == 'undefined') { 
     evt = window.event; 
    } 
    if (evt && evt.clientX >= (window.event.screenX - 150) && evt.clientY >= -150 && evt.clientY <= 0) { 
     return "Do you want to log out of your current session?"; 
    } 
} 

window.onbeforeunload = closeMe;