简体   繁体   English

如何覆盖onbeforeunload函数的默认弹出框

[英]How to override the default popup box of onbeforeunload function

I want to customize the default box to display my own fancybox form to make customer to subscribe for my website. 我想自定义默认框以显示我自己的fancybox表单,以使客户订阅我的网站。

In the below code, first it's displaying the default dialog box and then my form is displaying. 在下面的代码中,首先显示默认对话框,然后显示我的表单。 But I want to display my fancybox first. 但我想先显示我的fancybox。 I tried like below. 我尝试如下。 But I can't achieve output what I expected. 但是我无法实现预期的输出。 How can i solve this? 我该如何解决?

$(document).ready(function () {
    // Shadow box initialization
    Shadowbox.init({
        handleOversize: "resize",
        overlayOpacity: 0.9
    });

    // This makes sure that the pop up isn't shown
    // if the user is navigating within the website
    $(window).click(function () {
        window.onbeforeunload = null;
    });
    window.onbeforeunload = function (e) {
        //console.log(Event);
        //e.preventDefault();
        //e.defaultPrevented();

        //open thickbox
        Shadowbox.open({
            content: '<div id="welcome-msg">Welcome to my website!</div>',
            player: "html",
            width: 540,
            height: 380
        });
        return 'You have unsaved changes!';
    }
});

If you simply return the function, it will pop up the default confirm box. 如果仅返回该函数,它将弹出默认的确认框。

All you have to do is figure out when exactly will you want your 'fancy box' to be replaced by the default confirm box, and then return the message. 您所要做的就是弄清楚何时将您的“精美框”替换为默认的确认框,然后返回消息。

So instead of going straight to returning, wait for the user to make an action (subscribe/not subscribe) and then return the message. 因此,与其直接返回,不等用户进行操作(订阅/不订阅), 然后返回消息。

Perhaps you could create a global bool and return the message in the beforeunload event only if the bool is true . 也许您可以创建一个全局bool并且仅当布尔为true才在beforeunload事件中返回消息。

If you cannot or don't want to detect when they make an action, you could just place a timer; 如果您不能或不想检测他们何时采取行动,则可以放置一个计时器。 it's totally up to you. 这完全取决于您。

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

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