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.

Dirk Boer
  • 8,522
  • 13
  • 63
  • 111
  • 1
    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. – dandavis Mar 10 '15 at 16:29
  • Well, good point. I don't know *how* they do it, but they have also the back button working :) – Dirk Boer Mar 10 '15 at 16:53
  • 1
    **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). – Scott Mar 10 '15 at 16:54
  • 1
    They're probably using the history api and onpopstate https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate – Jonas Grumann Mar 10 '15 at 16:58
  • ok, make my comment read "only beforeunload() can prevent accidental _home_ button clicks"... – dandavis Mar 10 '15 at 17:01
  • @dandavis Apparently they have a fall back to the ugly dialog – Dirk Boer Mar 10 '15 at 17:06
  • so, getting back to the task, are you using the history API already? – dandavis Mar 10 '15 at 17:11
  • 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. – Dirk Boer Mar 10 '15 at 17:18

1 Answers1

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

      });
});
user3776738
  • 214
  • 2
  • 10
  • 27