Page 1 of 1

How to implement onbeforeunload correctly? [SOLVED]

Posted: Tue Mar 22, 2016 4:31 pm
by rkmore
I am having a tough time trying to figure out how to implement onbeforeunload.

For now I have managed to add it manually after compilation by going in and editing the generated HTML but there must be a better way to do it correctly.

Or am I missing something altogether? Is there some other mechanism to allow me to prevent the user accidentally navigating away?

In testing the users keep hitting the soft buttons (especially on a Samsung) and navigating away. I need to prevent that.

Thanks

RKM

Re: How to implement onbeforeunload correctly?

Posted: Wed Mar 23, 2016 9:28 am
by JS-Support @Userware
Hi,

Yes, you can prevent the user from accidentally leaving the application by registering the OnBeforeUnloaded event of the JavaScript "window" object. Doing so will cause a confirmation dialog to appear when the user attempts to close the app. The default text of the confirmation dialog is something like "Do you really want to leave?".

Rather than registering this JavaScript event manually by modifying the generated "index.html" file, I suggest that you register this JavaScript event from your C# code using the "Interop.ExecuteJavaScript" method (available in CSHTML5 1.0 beta 7.2 or newer).

For example, just add the following code to the constructor of App.xaml.cs:

Code: Select all

Interop.ExecuteJavaScript(@"
window.onbeforeunload = function (e) {
  var e = e || window.event;

  // For IE and Firefox
  if (e) {
    e.returnValue = 'Here you can append text to the default confirmation dialog text.';
  }

  // For Safari
  return 'Here you can append text to the default confirmation dialog text.';
}
");


Regards,
JS-Support

Re: How to implement onbeforeunload correctly?

Posted: Wed Mar 23, 2016 9:41 am
by rkmore
Works a treat. Thank you for the guidance.

RKM