ReedyBear's Blog

Prevent accidentally leaving new-post page

The below script will prevent you from leaving a blog post that you're in the midst of editing. It allows exit if you publish, save as draft, or Delete.

See my other Bearblog Tips & Tools

Visit https://bearblog.dev/dashboard/customise/ and paste the below code into the 'Dashboard footer content'.

<!-- Prevent accidentally leaving 'New Post' and 'Edit Post' page. -->
<script type="text/javascript">
window.addEventListener('beforeunload',
function(event) {
    const url = window.location.href;
    const body_content = document.getElementById("body_content");
    // Make sure we're on the NEW POST / EDIT POST page. 
    if (!url.includes('/dashboard/posts/')
       ||body_content == null) {
        //console.log("url not match or body_content null");
        return null;
    }

    const target = event.originalTarget.activeElement;
     
    // If you're submitting or deleting, we allow page exit
    if (target.getAttribute('type') == 'submit'
       || target.innerText == 'Delete') {
        //console.log("is a submission or deletion");
        return null;
    }

    //console.log("confirm exit");
    // it's a new/edit post (or page), so let's confirm you want to leave
    const msg = "Are you sure you want to leave this page?";
    // the .returnValue approach "is consistent across modern versions of Firefox, Safari, and Chrome." according to mdn, but I leave the return msg as a fallback for niche browsers in case they do it wrong.
    (event || window.event).returnValue = msg;
    return msg;
}
);

</script>

This is the 3rd iteration. Version 2. Version 1.

Note: It seems, at least in Firefox, if you load the page then try to leave without changing anything, then the exit-prevention doesn't work. Idunno why, I'm guessing onbeforeunload doesn't get called? It doesn't matter, since you don't lose any work.

#bearblog #featured