[SalesForce] How to pop-up alert to a user when he/she navigate away from page without saving the Records in custom visual force page

Question: How to pop-up alert to a user when he/she navigate away from page without saving the Records in custom visual force page?

Details:

I have a custom visual force page i.e. "My Members" that have the following code:

<apex:page Controller="MyMember" >
<script>

function mytest() {
 if (!confirm('Are you sure to naviagte without saving Records?')) {

 }
 else {return true;}
}

window.onbeforeunload = mytest();
</script>
<apex:form id="form">


 <apex:pageblock title="Member List" >

<apex:pageBlocktable value="{!CheckSelectedList}" var="memLst" >
<apex:column title="Select" >
<apex:inputCheckbox value="{!memLst.checked}" ></apex:inputcheckbox>
</apex:column>
<apex:column headerValue="Name" >
<apex:actionRegion >
<apex:outputField value="{!memLst.KeepSelected.Name}" >
<apex:inlineEditSupport event="ondblClick"
showOnEdit="btnSave,btnCancel" hideOnEdit="btnAddSession" />
</apex:outputField>
</apex:actionRegion>
</apex:column>

</apex:pageBlocktable> 
<apex:pageblockButtons>
<apex:commandButton value="Save" action="{!save}" id="btnSave"
 style="display:none" />
 <apex:commandButton value="Cancel" action="{!cancel}" id="btnCancel"
 style="display:none" reRender="PanelId" />
</apex:pageblockButtons> 
 </apex:pageblock>
</apex:form>
</apex:page>

In my VF Page, I have a in-line edit support enable.

The issue is:

Whenever, I want to alert user when they edit records and navigate without saving the record using JavaScript (Please see above the JavaScript code I was trying).
It doesn't seem to be working. Am I missing anything? Is it possible to do this using only JavaScript in Customer Visual Force Page?
Need:
I want when user edit the Record and leave the page without saving my function will execute and show the pop-up message.

My thoughts:

I was also thinking to execute my JavaScript function by using apex class?
Should it be possible?
Or any other technique how to invoke popup when the user navigate without saving the Edit records?

Best Answer

As @Mike Chale mentions above, this can be done using the beforeunload JavaScript event handler (which fires when you are trying to leave the page). If is often easiest to leverage a framework like jQuery to make the actual implementation as simple as possible on your end, but the most basic version of it would look like the following:

jQuery(window).on('beforeunload', function()
{
  return 'Leaving this page will lose your changes. Are you sure?';
}

This would prompt the user, who would then be given the option of leaving the page or canceling to stay on the page.

I had to implement this a while ago, and wrote a blog post on some of the more intricate parts (determining when you allow the user to leave a page -- typically on submit).

http://michaelwelburn.com/2013/04/08/confirming-a-user-really-wants-to-leave-a-visualforce-page/

Related Topic