How to implement onbeforeunload correctly? [SOLVED]

Please post public support tickets here. Note: for private support tickets, please send an email to support@cshtml5.com instead.
rkmore
Posts: 55
Joined: Mon Dec 07, 2015 1:53 pm

How to implement onbeforeunload correctly? [SOLVED]

Postby rkmore » Tue Mar 22, 2016 4:31 pm

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

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: How to implement onbeforeunload correctly?

Postby JS-Support @Userware » Wed Mar 23, 2016 9:28 am

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

rkmore
Posts: 55
Joined: Mon Dec 07, 2015 1:53 pm

Re: How to implement onbeforeunload correctly?

Postby rkmore » Wed Mar 23, 2016 9:41 am

Works a treat. Thank you for the guidance.

RKM


Return to “Technical Support”

Who is online

Users browsing this forum: No registered users and 58 guests

 

 

cron