Nafis Rahman
Nafis Rahman

Reputation: 55

event to be triggered when user leaves ckeditor or page

I have been trying to find an event that will trigger when a user leaves the ckeditor window or page in any way, this is because I want to call my save method inside the event so that when the user does try to leave their content is saved. I have inserted a conditional statement with an alert to test if its working but so far the alert hasn't been called signifying that the event I am currently using is not the correct one

here is my code block:

$(window).on('beforeunload', function() {
    updateBlockByName(blockname, escape(newhtml), 1, blockid, disableBlogComment);
    if (updateBlockByName) {
        alert('unload save test');
    }
});

any help is greatly appreciated

Upvotes: 2

Views: 661

Answers (1)

Comandeer
Comandeer

Reputation: 360

Actually beforeunload is broken pretty badly (probably by design) in Blink and it doesn't handle alert or other modal dialogs. If you want to display a message, you can use return:

$( window ).on( 'beforeunload', function() {
    return 'Message for the user';
}

It will display a confirm dialog with "Leave page" and "Stay on page" buttons.

Moreover, there is also the unload event, but it's as unreliable as beforeunload. And both of them don't work well on mobile devices.

Probably a good idea is not to rely on detecting the unloading of the page, but rather changes in visibility, via e.g. the pagehide event. It will also handle all cases when the user puts your page in the background and simply forgets about it.

A very detailed article about pagehide, beforeunload, unload and other similar events is available on Ilya Grigorik's site.

And if you want to detect only leaving the editor, you can probably just listen to CKEditor's blur event. It's fired when the user moves the cursor outside of the editor.

Upvotes: 1

Related Questions