在Javascript中停止刷新页面

时间:2013-12-14 12:54:15

标签: javascript html

此stopLeave func。被分配到'onbeforeunload'事件。当用户按取消时,如何阻止页面刷新或关闭资源管理器?

Javascript

    function stopLeave(){
    var a = confirm('are you sure you want to leave? you have unsaved work');
    if (a){
         what do i write here? } else
      {   what do i write here?
           }
     }

3 个答案:

答案 0 :(得分:0)

只需返回问题字符串:

window.onbeforeunload = function() {
    return "Are you sure you want to leave? you have unsaved work";
}

答案 1 :(得分:0)

您无法阻止用户关闭网页。您所能做的只是让浏览器询问用户是否要离开,如下所示:

$(window).on('beforeunload', function() { return 'are you sure you want to leave? you have unsaved work'; });

答案 2 :(得分:0)

尝试使用vanilla javascript进行此操作并确保跨浏览器兼容性:

function stopLeave(e){
    var message = 'Are you sure you want to leave?'; 
    var e = e || window.event;
    if (e) {
        e.returnValue = message ;
    }
    return message;
}