简体   繁体   English

关闭选项卡/浏览器之前的确认

[英]Confirmation before closing of tab/browser

How to ask confirmation from user before he leaves the page as in gmail?如何在用户离开页面之前要求用户确认,就像在 gmail 中一样?

I searched for this question in various places, but all that they mention is the use of javascript window.unload & window.onbeforeunload .我在各个地方搜索了这个问题,但他们提到的只是使用 javascript window.unload & window.onbeforeunload Also it doesn't work in chrome most of the times as it gets blocked.此外,它在大多数情况下都无法在 chrome 中工作,因为它被阻止了。

Try this:试试这个:

<script>
window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Sure?';
    }

    // For Safari
    return 'Sure?';
};
</script>

Here is a working jsFiddle这是一个有效的jsFiddle

Try this:试试这个:

<script>
    window.onbeforeunload = function(e) {
       return 'Dialog text here.';
    };
</script>

more info here MDN .更多信息在这里MDN

I read comments on answer set as Okay .我将答案集的评论阅读为OK Most of the user are asking that the button and some links click should be allowed.大多数用户都要求应该允许按钮和一些链接点击。 Here one more line is added to the existing code that will work.这里在现有代码中又添加了一行,可以正常工作。

<script type="text/javascript">
  var hook = true;
  window.onbeforeunload = function() {
    if (hook) {

      return "Did you save your stuff?"
    }
  }
  function unhook() {
    hook=false;
  }

Call unhook() onClick for button and links which you want to allow.调用 unhook() onClick 以获得您想要允许的按钮和链接。 Eg例如

<a href="#" onClick="unhook()">This link will allow navigation</a>

The shortest solution for the year 2020 (for those happy people who don't need to support IE) 2020年最短的解决方案(给那些不需要支持IE的快乐的人)

Tested in Chrome, Firefox, Safari.在 Chrome、Firefox、Safari 中测试。

function onBeforeUnload(e) {
    if (thereAreUnsavedChanges()) {
        e.preventDefault();
        e.returnValue = '';
        return;
    }

    delete e['returnValue'];
}

window.addEventListener('beforeunload', onBeforeUnload);

Actually no one modern browser (Chrome, Firefox, Safari) displays the "return value" as a question to user.实际上,没有一种现代浏览器(Chrome、Firefox、Safari)向用户显示“返回值”作为问题。 Instead they show their own confirmation text (it depends on browser).相反,他们显示自己的确认文本(这取决于浏览器)。 But we still need to return some (even empty) string to trigger that confirmation on Chrome.但是我们仍然需要返回一些(甚至是空的)字符串来触发 Chrome 上的确认。

More explanations see on MDN here and here .更多解释参见 MDN 此处此处

Simply简单地

function goodbye(e) {
        if(!e) e = window.event;
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
        }
    }
window.onbeforeunload=goodbye;

If you want to ask based on condition:如果您想根据条件询问:

var ask = true
window.onbeforeunload = function (e) {
    if(!ask) return null
    e = e || window.event;
    //old browsers
    if (e) {e.returnValue = 'Sure?';}
    //safari, chrome(chrome ignores text)
    return 'Sure?';
};
  1. Let say i want to close a window if nothing is selected假设我想关闭一个窗口,如果没有选择任何东西
  2. I want to close window with something selected but don't prompt me.我想用选定的东西关闭窗口,但不提示我。
  3. I want to close a window but something is selected prompt me plz.我想关闭一个窗口,但选择了一些东西提示我。

For these three conditions I have searched a lot in the following code made changes suit my needs hope help someone else.对于这三个条件,我在以下代码中进行了大量搜索,根据我的需要进行了更改,希望对其他人有所帮助。 ask is a key if I want to pop up the prompt 'true' will prompt you for close window other wise not.如果我想弹出提示“true”,ask 是一个关键,否则会提示您关闭窗口。 Suppose I want to print my document and redirect my page the ask will be false and there will be no prompt.假设我想打印我的文档并重定向我的页面,询问将是假的,并且不会有提示。 Suppose your page having data then check a condition is my case a value subtotal if subtotal is zero then no prompt other wise prompt me that you have something in your page.假设您的页面有数据,然后检查条件是我的情况,如果小计为零,则没有提示,否则会提示我您的页面中有内容。

<pre>
    var ask = true;
    window.onbeforeunload = function(e) {
       if (!ask) return null
       var subtotal = $('#lblgtwithsgst').text();
         if (subtotal != '0') {
          e = e || window.event;
          //old browsers
            if (e) {
             e.returnValue = 'Sure?';
            }
            //safari, chrome(chrome ignores text)
            return 'Sure?';
         }  
      }
      $('#btnPrint').click(function(){
        ask = false;
        ///print your doc no prompt if ask is false;
      )};
// use jquery version older than 1.6    
    var preventUnloadPrompt;
    var messageBeforeUnload = "my message here - Are you sure you want to leave this page?";
    $('a').live('click', function() { preventUnloadPrompt = true; });
    $('form').live('submit', function() { preventUnloadPrompt = true; });


    $(window).bind("beforeunload", function(e) { 
        
        var rval;
        if(preventUnloadPrompt) {
            return;

        } else {
            

            return messageBeforeUnload;
        }

        return rval;
    })

For Angular, Change with component form name and paste in component where you need to display alert.对于 Angular,更改组件表单名称并粘贴到需要显示警报的组件中。

  @HostListener('window:beforeunload', ['$event'])
  beforeunloadHandler(event) {
    return !this.form.dirty;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM