Formyoula Guides 📖
Formyoula Guides 📖
/
Custom JavaScript Example To Sign Out Inactive Users

Custom JavaScript Example To Sign Out Inactive Users

The following JavaScript code will check if the current user has been active over the past n hours. If the user is inactive for n hours, the mobile application will sign out the logged-in user.

Please add below JavaScript code on your Formyoula form deployed to your users.

image
( function() {
  // Check if JavaScript already loaded
  if ( !window[ 'formyoula_js_set_interval_check_if_user_is_active_in_last_n_hours' ] ) {
    // Set the number of hours of inactivity before logout
    var hours_of_inactivity_before_logout = 8;
    // Set current time
    window[ 'formyoula_js_last_activity_time_for_user_logout_check' ] = new Date();
    // Add event listeners to check for inactivity
    document.addEventListener( 'mousedown', set_last_activity_time, false );
    document.addEventListener( 'keydown', set_last_activity_time, false );
    // Register event for touch devices
    document.addEventListener( 'touchend', set_last_activity_time, false );
    document.addEventListener( 'touchmove', set_last_activity_time, false );
    // Set time when last activity occured
    function set_last_activity_time() {
      // Set current time
      window[ 'formyoula_js_last_activity_time_for_user_logout_check' ] = new Date();
    }
    // Start Interval
    window[ 'formyoula_js_set_interval_check_if_user_is_active_in_last_n_hours' ] = setInterval( function() {
      // Check if Formyoula user has a Salesforce Id
      if ( window.formyoula.user ) {
        // Run main check function
        check_if_user_is_active_in_last_n_hours();
      }
    }, 1000 * 60 * 30 ); // END Interval
    // Function for checking active user
    function check_if_user_is_active_in_last_n_hours() {
      // Check if error has the inactive description
      if ( moment().diff( moment( window[ 'formyoula_js_last_activity_time_for_user_logout_check' ] ), 'hours' ) > hours_of_inactivity_before_logout ) {
        // Trigger signout
        window.formyoula.event_trigger( 'sync:clear_all', {} );
        window.formyoula.event_trigger( 'login:main', {} );
        // Remove user details
        delete window.formyoula.user;
      }
    }
  }
} )();

For any questions, please contact us - [email protected] or the Formyoula in-app chat 🙂