Should onbeforeunload work in GWT JSNI?

1,059 views
Skip to first unread message

Damon Lundin

unread,
Dec 16, 2009, 12:42:02 PM12/16/09
to Google Web Toolkit
I have a need to implement a "Are you sure you want to leave?"
functionality that can prevent the user from leaving the page (the
same thing Gmail does) when there is unsaved data. All the
documentation I've read says that you can do this by returning a
string from the window.onbeforeunload method. This works if I embed
raw javascript in my html page, but it doesn't seem to work when I
make a native GWT method to do that same thing.

This works:
<script type="text/javascript">
window.onbeforeunload = function () {
return "Hello (in the browser)";
};
</script>


This doesn't:
private native String addOnBeforeUnloadHandler() /*-{
$wnd.onbeforeunload = function () {
return "Hello (in GWT)";
};
}-*/;

Any idea why (and I added an alert in that method to verify that it is
being called to add the onbeforeunload)?

If I have to, I can embed the raw script in the HTML and add a hook
into my GWT code, but that's not as pretty.

Thomas Broyer

unread,
Dec 16, 2009, 7:03:16 PM12/16/09
to Google Web Toolkit

On 16 déc, 18:42, Damon Lundin <damon.lun...@gmail.com> wrote:
> I have a need to implement a "Are you sure you want to leave?"
> functionality that can prevent the user from leaving the page (the
> same thing Gmail does) when there is unsaved data.  All the
> documentation I've read says that you can do this by returning a
> string from the window.onbeforeunload method.  This works if I embed
> raw javascript in my html page, but it doesn't seem to work when I
> make a native GWT method to do that same thing.

In GWT, use Window.addWindowClosingHandler and setMessage on the
Window.ClosingEvent.

Damon Lundin

unread,
Dec 17, 2009, 11:19:59 AM12/17/09
to Google Web Toolkit
> In GWT, use Window.addWindowClosingHandler and setMessage on the
> Window.ClosingEvent.

Well, how about that? That works. Thank you very much!

I'm still a little curious though why the JSNI version doesn't work.

Brett Slocum

unread,
Sep 28, 2012, 2:46:36 PM9/28/12
to google-we...@googlegroups.com
I tried this solution and it worked, but I wanted to make this only create the popup dialog under some circumstances (like testing a boolean into the onbeforeunload function before returning a string). I tried adding a boolean to my EntryPoint and then setting it from the right piece of code, but that never worked.

Anyone have insight?

Brett
Reply all
Reply to author
Forward
0 new messages