Opening as subTabs in Cloud Console using Visualforce Pages

This Post explains how to Open Records in subtabs in Console app of Salesforce.

Following page works on both console and normal apps, explained in 3 steps,

  1. Script - responsible for calling methods
  2. Markups - Html/Visualforce tags to call scripts
  3. Full Page - Final Page Preview

1. Script

// this is mandatory
<apex:includeScript value="/support/console/29.0/integration.js"/>

// call 'openSubTab' function with only one parameters 'recordId'
function openSubTab(recId) {
    var redirectUrl = recId;
    
    // condition to check for Console
    if (sforce.console.isInConsole()) {
        sforce.console.getEnclosingTabId(function(enclosingResult) {
            sforce.console.getEnclosingPrimaryTabId(function(primaryResult) {
                sforce.console.openSubtab(primaryResult.id, redirectUrl, true, '', null);
            });
        });
    } else { // other than console
        // for inline Vf
        window.top.location.href = '/' + redirectUrl
        // for normal vf
        // window.location.href = '/'+redirectUrl
    }
}

2. Markups

 <a href="#" onclick="openSubTab('<recordId>');">Click Me</a>

3. Final Preview

<apex:page standardController="Account" extensions="accHierarachy_Ext">
    <apex:includeScript value="/support/console/29.0/integration.js"/>
    <script type="text/javascript">       	
        function openSubTab(recId){
            var redirectUrl = recId;
            if (sforce.console.isInConsole()) {
                sforce.console.getEnclosingTabId(function(enclosingResult){
                    sforce.console.getEnclosingPrimaryTabId(function(primaryResult){
                        sforce.console.openSubtab(primaryResult.id, redirectUrl, true, '', null);
                    });
                });
            } else {
            	// for inline Vf
                window.top.location.href = '/'+redirectUrl
                // for normal vf
                // window.location.href = '/'+redirectUrl
            }
    	}        
    </script>
    <apex:pageBlock >
    	<apex:pageBlockTable value="{!activitiesList}" var="a">
            <apex:column headerValue="Subject">              
                <a href="#" onclick="openSubTab('{!a.Id}');">{!a.Subject}</a>
                <!-- here onClick() is responsible for opening in subtab -->
            </apex:column>            
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Please feel free to comment below if you face any problems

Thanks,