function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
OdedHarnivOdedHarniv 

Executing some code when leaving a VF page

Hello

 

I need some expert advice...

 

I want to have some code to be executed once the user leaves a VF page.

My case is that I want to save some changes the user makes to the page only when the user leaves the page to avoid multiple database calls.

 

Is there any way I can do that?

 

Thanks

 

Oded

Best Answer chosen by Admin (Salesforce Developers) 
Shashikant SharmaShashikant Sharma

add this script to your vfp, in this I have used window.onbeforeunload event

 

<script>
function closeIt()
{
  return "Call Action function here";
}
window.onbeforeunload = closeIt;
</script>

 

 this will show an alert every time user leave the page but you just need to call an actionFunction to save the data instead of alert. Let me know if any issues in it.

All Answers

Shashikant SharmaShashikant Sharma

Do you count browser actions like closing the window or navigating forward or backwards using browser as well the case of leaving the page and do you want to save info in that case as well.

OdedHarnivOdedHarniv

Yes, I want to make the DB call only when the user closes, navigates back or forward or leaves the page

 

Do you have any idea what should I do?

 

Thanks

 

Oded

Shashikant SharmaShashikant Sharma

add this script to your vfp, in this I have used window.onbeforeunload event

 

<script>
function closeIt()
{
  return "Call Action function here";
}
window.onbeforeunload = closeIt;
</script>

 

 this will show an alert every time user leave the page but you just need to call an actionFunction to save the data instead of alert. Let me know if any issues in it.

This was selected as the best answer
OdedHarnivOdedHarniv

Thank you very much

Shashikant SharmaShashikant Sharma

Your Welcome Mate