Run javascript when user closes a page?

  • 1
  • Question
  • Updated 4 years ago
  • Answered
Is there any way to accomplish something like this?

Basically, after our users are finished with a page I want to evaluate some fields and perform a few actions on the values of those fields. But the fields might change several times, and I only want to run the script once, so I can't really use a model action... unless I'm missing something?

I can create a 'close' button that runs multiple actions... but this doesn't account for users closing the window. Do I have to just train our users to never close their browser windows, and always use the 'close' button?

Thanks!
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb

Posted 4 years ago

  • 1
Photo of Zach McElrath

Zach McElrath, Employee

  • 49,056 Points 20k badge 2x thumb
You can use the window onbeforeunload event.

$(window).on('beforeunload',function(){
   // If returnMessage is never defined, no warning message will be thrown
   var returnMessage;
   $.each(skuid.model.getModel('Contacts').getRows(),function(i,row){
      if (!row.FirstName) {
          returnMessage = 'One or more Contacts does not have a FirstName. Are you sure you want to leave the page without giving them a First Name?';
          return false;
      }
   });
   return returnMessage;
});




More more details, see the docs:

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb
Sweet! Thanks, Zach!