Note: Advice in this article will only work for JxBrowser 6. See the corresponding article for JxBrowser 7 here.(注意:本文中的建议仅适用于JxBrowser6,JxBrowser7相应文章请点击这里。)


The onbeforeunload event fires when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. JxBrowser API allows handling this dialog using DialogHandler API. By default the dialog is displayed. Using your custom implementation of the DialogHandler, you can handle this dialog in your own way. For example, you can display your custom message dialog or suppress the dialog and don't allow unloading web page.(即将卸载文档时,将触发onb​​eforeunload事件。此事件使您可以在确认对话框中显示一条消息,以通知用户他/她/它想停留还是离开当前页面。 JxBrowser API允许使用DialogHandler API处理此对话框。默认情况下,显示对话框。使用DialogHandler的自定义实现,您可以用自己的方式处理此对话框。例如,您可以显示您的自定义消息对话框或隐藏该对话框,并且不允许卸载网页。)


The following sample demonstrates how to handle the onbeforeunload dialog: (下面的示例演示如何处理onbeforeunload对话框:)

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.CloseStatus;
import com.teamdev.jxbrowser.chromium.UnloadDialogParams;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.DefaultDialogHandler;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to catch onbeforeunload dialog.
 */
public class BeforeUnloadSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        final BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setVisible(true);

        browser.setDialogHandler(new DefaultDialogHandler(view) {
            @Override
            public CloseStatus onBeforeUnload(UnloadDialogParams params) {
                String title = "Confirm Navigation";
                String message = params.getMessage();
                int returnValue = JOptionPane.showConfirmDialog(view, message, title, JOptionPane.OK_CANCEL_OPTION);
                if (returnValue == JOptionPane.OK_OPTION) {
                    return CloseStatus.OK;
                } else {
                    return CloseStatus.CANCEL;
                }
            }
        });
        browser.loadHTML("<html><body onbeforeunload='return myFunction()'>" +
                "<a href='http://www.google.com'>Click here to leave</a>" +
                "<script>function myFunction() { return 'Leave this web page?'; }" +
                "</script></body></html>");
    }
}