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
Serena SchultzSerena Schultz 

Javascript to unload page before navigating away from a customer community page

I have a customer community with a form embedded on a custom page. I have javascript included in the form which will autosubmit the form if the user hits the back button or the refresh button on their browser. The javascript will also timeout to the homepage after a set time delay to force the autosubmission of the form.

The goal is to autosubmit forms before a user accidentally navigates away, closes or refreshs their browser tab, or leaves the page open longer than their SF session time limit.

My code (below) is working for all scenarios EXCEPT when a user manually navigates away from the form page by clicking another tab in the navigation, etc.

I want to update it so that it will run on timeout, browser back, browser reload, browser close, AND user navigates away.

Any ideas oh wise dev community? Thanks in advance!
 
function updateRequiredFields() 

   fs('input,textarea,select').each(function(){
        if(fs(this).attr('data-isrequired')=='true' && fs(this).val()==""){ 
             fs(this).attr('data-isrequired','false');
        }
});


window.onbeforeunload = function() {
   updateRequiredFields();
   SubmitData();
console.log("data submitted");
  };

setTimeout(function(){ location.replace("https://community-pathfoundation.cs14.force.com/granteeportal/s/") }, 30000);