Friday, March 22, 2013

Handle Session Timeout on Visual Force Page

One of my fellow developer recently faced a strange requirement related to handling session timeout on visualforce page. They have quite large Visual force page with lot of data entry fields. Sometime it take hours to fill that large form.

Although Salesforce session timeout duration can be increased and salesforce give option to continue your previous session also. But still there are chances that user doesn't notice session timeout popup or may be they have popup blocker enable in their browser. In such cases session timeout popup will not appear at all, and this vary browser to browser.

So he wanted to do something when user hit submit/save button to verify if session is active otherwise give error message and stay on page. Although once session has expired there is no way to post the data entered on that form even if you relogin in same browser. But if we give a error message in javascript and stay on page data is still there that they can copy/paste on a new form.

A practical use case for this problem is when you are capturing from client on phone, so you would not like to bother client again complaining that my session expired. Here is a workaround to this problem.

<apex:page standardController="Account">
  <script src="/soap/ajax/27.0/connection.js" />
    <script>
      function saveRecord(){
        try{
          sforce.connection.sessionId = "{!$Api.Session_ID}";
          var result = sforce.connection.query("Select Name, Id from User Limit 1");
          if(result)
            return true;
          else
            return false;      
        }
        catch(ex){
          if(ex.faultcode == 'sf:INVALID_SESSION_ID')
            alert('Your session has expired, data will not be saved.');
          else
            alert(ex);
          return false;
        }
      }
    </script>
  <apex:form >
    <apex:inputField value="{!Account.Name}" />
    <apex:commandButton action="{!save}" value="Save" onclick="return saveRecord();" />
  </apex:form>
</apex:page>

2 comments:

  1. Thanks Amit.
    Any idea on how to auto re-login the portal user when session is timed out ? .
    Appreciate your response in advance.

    ReplyDelete
  2. Hi Amit,
    I have implement such a long visual force page with jquery .I kept the action poller to keep the session alive.This is working for me.But i have a lot of rendering in the page that the entire page snaps if cause two rendering to cause at the same time.This issue only happens in IE browser.Do you have any ideas around this is much appreciated.

    ReplyDelete