【问题标题】:How to show popup when user closes the browser tab?用户关闭浏览器选项卡时如何显示弹出窗口?
【发布时间】:2020-02-25 14:41:33
【问题描述】:

关闭浏览器选项卡时有什么方法可以显示弹出窗口吗?在弹出窗口中应该有一个按钮可以查看更多内容,当用户单击该按钮时,用户应该被重定向到查看更多页面。如果用户单击弹出窗口中的取消按钮,用户将离开网站。有没有办法做到这一点?我目前正在尝试此代码。它显示了弹出窗口,但它突然消失了。我认为条件也不起作用。

    var userclicked=false;
    window.onbeforeunload = function(e) {
        //e.preventDefault();
        if(!document.hasfocus()){

        Swal.fire({
            title: 'New Promotions!',
            text: 'Visit to See New Promotions!',
            type: 'info',
            showCancelButton: true,
            confirmButtonText: 'View More',
            cancelButtonText: 'Cancel',
            showCloseButton: true
        }).then((result) => {
            if (result.value) {  userclicked=true;
                window.location = "{{url('front/promotionpage')}}";                
            } else if (result.dismiss === Swal.DismissReason.cancel) {    userclicked=true;            
            }
        });            

        if(userclicked){
            return "Hi";
        }else{
            return null;
        }
        }

        //return "hi";

        //window.onbeforeunload = null;
        //return null;
        //return "Hi";
    }

【问题讨论】:

标签: javascript jquery laravel


【解决方案1】:

您可以添加这个简单的代码。当您要关闭浏览器窗口时,它会显示警报。

window.onbeforeunload = function() {
    var message = 'Do you want to leave this page?';
    return message;
}

【讨论】:

  • 请注意,message 文本在大多数浏览器中将被完全忽略。
【解决方案2】:

当窗口、文档和它的 资源即将被卸载。该文档仍然可见并且 此时活动仍可取消。 DOC

 window.addEventListener('beforeunload', (event) => {
      // Cancel the event as stated by the standard.
      event.preventDefault();
      // Chrome requires returnValue to be set.
      event.returnValue = '';
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 2016-07-11
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多