[SOLVED][Drupal] Quicktab cookie is not persisting after closing and re-opening browser.

| | 2 min read

On one of the Drupal projects we had recently worked on, the client wanted us track the last active tab. We had used the Drupal Quicktab module to create the tabs. However we noticed that the quicktab cookie used to track the last active tab is not persisting after closing and reopening the browser. If you are facing the same scenario in your Drupal site and want to know the solution then continue reading.

To make the Quicktab cookie persist after closing and re-opening browser we need to make changes in quicktab.js. Follow the steps below to solve the issue.

  • First add the following code to set the cookie for the current active tab.
    Drupal.behaviors.quicktabs = function (context) { ....
     
      $('#block-quicktabs-1 #quicktabs-1 ul li a').click(function() {
        var active_tab_id = this.id.split('-')[3];
        // SetCookie for alerts:
        setCookie('quicktabs',active_tab_id,365);
    		return false;
      });
      $('#quicktabs-2 ul li a').click(function() {
        var active_tab_id = this.id.split('-')[3];
        // SetCookie for alerts:
        setCookie('quicktabs',active_tab_id,365);
        return false;
      });
    };
  • Next we need to get the cookie to highlight the active tab
    // setting up the inital behaviours
    Drupal.quicktabs.prepare = function(el) { .....
      // Search for the active tab.
      var $active_tab = $(el).children('.quicktabs_tabs').find('li.active a');
    
      var cookie_name  = "quicktabs";
      
      if ( document.cookie.length > 0 ) {
        // Get cookie..
        active_tab    = getCookie(cookie_name);
       
        var active_id = "quicktabs-tab-" + qtid + "-" + active_tab;
        $(el).children('.quicktabs_tabs').find("a#" + active_id).trigger('click');
      }
      else if ($active_tab.hasClass('qt_tab') || $active_tab.hasClass('qt_ajax_tab')) {........
  • The setCookie function was edited to work in Safari
    function setCookie(c_name,value,exdays) {
      var exdate=new Date();
      exdate.setDate(exdate.getDate() + exdays);
      //var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString())+'; path=/';
      var c_value=escape(value) + "; expires="+exdate.toUTCString()+"; path=/";
    	document.cookie=c_name + "=" + c_value;
    }
    
  • The getCookie function
    function getCookie(c_name) {
      var i,x,y,ARRcookies=document.cookie.split(";");
      for (i=0;i < ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
          return unescape(y);
        }
      }
    }
    

References:

  1. How do I create and read a value from cookie in JavaScript?
  2. Using JavaScript Cookies as Global Variables