+ Start a Discussion
SFDC coderSFDC coder 

show javascript popup when user navigates away from page

hi all,

i have a requirement where in i want to alert a user whenever the user navigates away from the webpage without clicking on save button and navigating away instead of that..i tried the below code but its not working..
below is my code

 
<apex:page controller="VistAudit_VFC" action="{!createData}">
<body onload="myfunction()">
<script>
function myFunction()
{
alert("Are you sure you want to navigate away?");
}
</script>

     <apex:form >
  <apex:outputLabel value="Audit Visit" style="font-family:Times New Roman;font-size:18px"></apex:outputLabel><br></br>
 
    <div align="center" draggable="false" >
    <apex:commandButton value="Save" action="{!save}" onclick="myFunction();"/>
    </div>
..........
...........
.......
</apex:form>
</body>
</apex:page>

Can anyone please suggest as to how can i correct my code?


thanks,
 
Boris BachovskiBoris Bachovski
If you want to notify the user when they try to close the tab/page you need to use the "onbeforeunload" event, stick the following code inside your script tags:
 
window.onbeforeunload = function (e){
  return confirm('Are you sure you want to leave the page?');
};
Alternatively if you want to show a confirm message when they just leave the tab/page (lose focus) you need to use the "onblur" and "onfocus" events:
 
var showConfirm = true; 

window.onblur = function () { 
   if (showConfirm) 
   { 
        if(confirm('Are you sure you want to leave the page?')) 
            showConfirm = false;
   } 
};

window.onfocus = function () { 
    // Check whether they've clicked save and set this variable appropriately    
    showConfirm = true; 
}


 
SFDC coderSFDC coder
thanks a ton Boris Bachovski!!!
your first patch seems to be working for mee.
However just some minor issues

1.i get the pop up everytime the user navigates away,but when the user reloads and gets the pop up,then after i click on leave this page
   it still reloads the same page.what can be the reason?
2.my pop up displays a boolean value false and then the message on the next line .How do i get rid of that boolean value?

User-added image

thanks
Boris BachovskiBoris Bachovski
I have found a better cross browser solution for that. Try this
 
var evt = window.attachEvent || window.addEventListener;
var checkEvt = window.attachEvent ? 'onbeforeunload' : 'beforeunload';
evt(checkEvt, function(e) { 
    var msg = 'Are you sure you want to leave the page?';
    (e || window.event).returnValue = msg;
    return msg;
});

 
SFDC coderSFDC coder
User-added image

thanks for your assistance... :)
but this is what i get...any help on this?
Boris BachovskiBoris Bachovski
var msg = 'Are you sure you want to leave the page?';
that's your additional custom message that you want to display to the user. If you don't want anything else apart from "Are you sure that you want to leave this page?" then set the msg variable to an empty string:
 
var msg = '';


 
SFDC coderSFDC coder
thanks Boris Bachovski..
Still there are 2 issues..

1.the pop up arises,even when i click on my apex:command button save.I want it to pop up only when the  user navigates away without saving        anything.Is this doable?

2.The earlier issue i.e when the user clicks on F5 or reloads the page,the pop up arises and when clicked on leave this page,it reloads the same page again.

Can you suggest something over these two?

Thanks..
Boris BachovskiBoris Bachovski
Here is the code based on what you've provided. Please put some effort and research into this, I'm sure you'll work out the next issues yourself.
 
<apex:page controller="VistAudit_VFC" action="{!createData}">
<body>
<script>
	var buttonClicked = false;
	var evt = window.attachEvent || window.addEventListener;
	var checkEvt = window.attachEvent ? 'onbeforeunload' : 'beforeunload';
	evt(checkEvt, function(e) {
		if (!buttonClicked)
		{
		    var msg = 'Are you sure you want to leave the page?';
		    (e || window.event).returnValue = msg;
		    return msg;
		}
	});

	function myFunction()
	{
		buttonClicked = true;
	}
</script>
 
    <apex:form >
	  	<apex:outputLabel value="Audit Visit" style="font-family:Times New Roman;font-size:18px"></apex:outputLabel><br></br>
	  
	    <div align="center" draggable="false" >
		    <apex:commandButton value="Save" action="{!save}" oncomplete="myFunction();"/>
	    </div>
	</apex:form>
</body>
</apex:page>

 
Navee RahulNavee Rahul

Hi SFDC coder,

one doubt you want that alert message in particular page alone ??


Thanks
D Naveen Rahul.

SFDC coderSFDC coder
hi rahul,
yes i want in that particular page only
Navee RahulNavee Rahul

Hi SFDC,

looks like this what you were expecting.

<apex:page standardController="Account" recordSetVar="accounts" sidebar="false">
<script>
 
 function dontleave(e) {
    if(!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
window.onbeforeunload=dontleave;
</script>
  <apex:pageBlock >
    <apex:pageBlockTable value="{!accounts}" var="a">
          <apex:column value="{!a.name}"/>

          <apex:column >
             <apex:outputLink value="/apex/View_Account_detail?id={!a.Id}" id="theLink">View detail</apex:outputLink>
         </apex:column>
         <apex:column >
             <apex:outputLink value="/apex/View_Account?id={!a.Id}" >View</apex:outputLink>
         </apex:column>
          
    </apex:pageBlockTable>
  </apex:pageBlock>
</apex:page>

 

Mark it closed if this anwer helps you.

Thanks
D Naveen Rahul.

SFDC coderSFDC coder
hey thanks navve rahul,

but still am facing those two issues


1.the pop up arises,even when i click on my apex:command button save.I want it to pop up only when the  user navigates away without saving        anything.Is this doable?

2.The earlier issue i.e when the user clicks on F5 or reloads the page,the pop up arises and when clicked on leave this page,it reloads the same page again.
 
SFDC coderSFDC coder
hi boris,

just one question..from where do you get the value for variable e?which you have passed in function(e)?
You see am not good at all in javascript

Thanks..
Navee RahulNavee Rahul

The below will work like what you expecting now ,the only diference is the texts in the popup.

<apex:page standardController="Account" recordSetVar="accounts" sidebar="false">
<script>

window.twotimer=    function() {
    eventSrcID=(event.srcElement)?event.srcElement.id:'undefined';
    eventtype=event.type;
    status=eventSrcID+' has received a '+eventtype+' event.';
    if(event.srcElement.innerHTML=='Accounts'){
       if(confirm("Are you sure you want to navigate away from this page?"))
       {
         
       }else{
           return false;
       } 
       
    }
}

document.onclick= twotimer;

</script>
  <apex:pageBlock >
    <apex:pageBlockTable value="{!accounts}" var="a">
          <apex:column value="{!a.name}"/>

          <apex:column >
             <apex:outputLink value="/apex/View_Account_detail?id={!a.Id}" id="theLink">View detail</apex:outputLink>
         </apex:column>
         <apex:column >
             <apex:outputLink value="/apex/View_Account?id={!a.Id}" >View</apex:outputLink>
         </apex:column>
          
    </apex:pageBlockTable>
  </apex:pageBlock>
</apex:page>

SFDC coderSFDC coder
hey navee rahul,

my problem is not with the text now..its just that when i click on save button,also i get the pop up which is not an ideal solution.
the pop up should only arise when someone navigates away from the page
for eg:clicks on some other link or closes the tab or clicks backward/forward buttons on browsers and such actions 
Navee RahulNavee Rahul

HI,

SDFC coder the  codes work right 
 

<script>

window.twotimer=    function() {
    eventSrcID=(event.srcElement)?event.srcElement.id:'undefined';
    eventtype=event.type;
    status=eventSrcID+' has received a '+eventtype+' event.';
   i just hardcoded the link name below for account tab you can change it to what ever u need  
    if(event.srcElement.innerHTML=='Accounts'){
       if(confirm("Are you sure you want to navigate away from this page?"))
       {
         
       }else{
           return false;
       } 
       
    }
}

document.onclick= twotimer;

</script>

Navee RahulNavee Rahul

my skype naveen_rahul for more detail.

Thanks
D Naveen Rahul.

SFDC coderSFDC coder
ok so how will this work for me in my vf page?
i dont want to display the pop up when clicked on save button
 
<apex:page controller="VistAudit_VFC" action="{!createData}">
<script>
window.twotimer=    function() {
    eventSrcID=(event.srcElement)?event.srcElement.id:'undefined';
    eventtype=event.type;
    status=eventSrcID+' has received a '+eventtype+' event.';
   i just hardcoded the link name below for account tab you can change it to what ever u need  
    if(event.srcElement.innerHTML=='Mybtn'){
       if(confirm("Are you sure you want to navigate away from this page?"))
       {
         
       }else{
           return false;
       } 
       
    }
}

document.onclick= twotimer;

</script>

     <apex:form id="myform">
  <apex:outputLabel value="Audit Visit" style="font-family:Times New Roman;font-size:18px"></apex:outputLabel><br></br>
 
    <div align="center" draggable="false" >
    <apex:commandButton value="Save" action="{!save}"/>
    </div>
    
    <apex:pageBlock >
    <apex:pageBlockSection >
    <apex:inputField value="{!relatedEvent.Notes__c}" style="height:40px"/>
    <apex:inputText value="{!relatedEvent.Previous_Event_Notes__c }" disabled="true" style="height:40px"/>
    </apex:pageBlockSection>
    
    </apex:pageBlock>
    ...
.................
................

highlighted above is my button..
ksmoksmo
Hi SFDC Coder,

Did you get a solution for this?

I want the popup to appear only when the user navigates away from the page without clicking the save button.

Thanks,
Lance Havens 13Lance Havens 13
I can get this to work when the user changes data on the main detail record. However, if they have started typing an email the message does not display and the user looses their work. See screenshot below: 
User-added image