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

时间:2014-09-20 06:51:22

标签: javascript jquery

我想自定义默认框以显示我自己的fancybox表单,以便客户订阅我的网站。

在下面的代码中,首先显示默认对话框,然后显示我的表单。但我想先显示我的fancybox。我尝试过如下。但我无法实现我所期望的输出。我该如何解决这个问题?

$(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!';
    }
});

1 个答案:

答案 0 :(得分:0)

如果您只是返回该功能,它将弹出默认确认框。

你需要做的就是弄明白什么时候你想要你的奇特盒子&#39;要被默认确认框替换,然后返回消息。

因此,不要直接返回,而是等待用户进行操作(订阅/不订阅),然后返回消息。

也许你可以创建一个全局bool,并且只有当bool为beforeunload时才会在true事件中返回消息。

如果您不能或不想检测他们何时采取行动,您可以放置​​一个计时器;它完全取决于你。