Detect tab/window/broswer close event

Hello,

I want to detect the window/tab close event, to clear some server side parameters and initialize the connection, i found this code in the forum, but i have 2 problemes:

  1. When i close the tab, ok, but i don’t receive the event when i close the application firefox directly.
  2. When i create a sub window to show the detail information or to download a file on the main page, the event is also sent, why?
    Thank you.
MainUI:
this.addDetachListener(new DetachListener() {
            public void detach(DetachEvent event) {
                System.out.println("######### Detached ##########");
            }
        });
        JavaScript.getCurrent().addFunction("aboutToClose", new JavaScriptFunction() {
            @Override
            public void call(org.json.JSONArray arguments)
                    throws org.json.JSONException {
                System.out.println("Window/Tab is Closed.");
                //TODO Call Method to Clean the Resource before window/Tab Close.
            }
        });
         Page.getCurrent().getJavaScript().execute("window.onbeforeunload = function (e[code]
) { var e = e || window.event; aboutToClose(); return; };");

[/code]

This work:

String js = "window.addEventListener(\"beforeunload\", function () {"+
				"aboutToClose();"+
			"});";

Page.getCurrent().getJavaScript().execute(js);