What is the most unobtrusive way to implement a custom 'beforeunload' dialog?
Asked Answered
E

1

8

I'm talking about a styled dialog, instead of the default 'beforeunload' dialog that can't be styled.

See Facebook: Facebook unload image

What is the most unobtrusive way to make this? Preferrable some script that I declare once, and magically always works.

I'm think about something in the line of:

function showCustomDialog()
{
    [...]
}

var unfinished = true;

$('a').click(function()
{
    if ( unfinished )
    {
        window.showCustomDialog( { originalUrl: $(this).attr('href') } );
        return false;
    }
}

But I'm affraid this will break cases where i.e. a <a> element is used for triggering JS-behaviour, or where JavaScript triggers a window.location.href change.

Is there a better, non-obtrusive way?

Extra note - They also got it working for the back button.

Extra note - Apparently they fall back to the default dialog when it's out of their control.

Emerick answered 10/3, 2015 at 16:26 Comment(8)
only beforeunload() can prevent accidental back button clicks. i agree it could look nicer, but the default does take the user's theme and looks like they expect. you would lose usability and functionality by customizing it.Triolet
Well, good point. I don't know how they do it, but they have also the back button working :)Emerick
Brain dump: Facebook probably serves/loads pages different than normal webservers, allowing them to have full control over everything. This is how some elements, like the chat bar, stay persistent while the rest of the content loads. In order to implement this yourself, you could have all your pages load themselves through AJAX, set the content, and update the URL with history.replaceState. As for the back button, they're probably using onbeforeunload to trigger the previous request (breadcrumbs).Amaty
They're probably using the history api and onpopstate developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/…Frisby
ok, make my comment read "only beforeunload() can prevent accidental home button clicks"...Triolet
@Triolet Apparently they have a fall back to the ugly dialogEmerick
so, getting back to the task, are you using the history API already?Triolet
not yet - i might implement it later for parts of specific pages though. But for very different pages I have a full page refresh atm.Emerick
R
0

I think the main problem is,that you can't predict every change in the DOM,so you can just easily refresh with every mousemove-event (touch-event for smartphones etc..) like this:

$(document).off('mousemove').mousemove(function(){
      $('a').off('click').click(function(e){
           e.preventDefault();

           //your dialog goes here

      });
});
Retardment answered 27/4, 2015 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.