A whole new level of customization with Custom Buttons

April 15, 2015

One of the various behaviors of Custom Button is "Execute JavaScript", with a content source of OnClick JavaScript.

They can not only execute javascript Functions On Click, but you can make Javascript execute on page load too.

The main use for this being complete control over every element in the object detail page without user clicking a button. We use jQuery for this.

We begin by importing the required jQuery files.

{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js')}
{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js')}

Optionally you have to import connection.js and apex.js if you want to perform any operations using sforce.

{!REQUIRESCRIPT('/soap/ajax/29.0/connection.js')}
{!REQUIRESCRIPT('/soap/ajax/29.0/apex.js')}

Below is the jQuery code which hides a button and triggers the click of a button.

var j$ = jQuery.noConflict();
j$(document).ready(function(){
j$("input[name=**btn_Name**]").css('display','none');
j$("input[name=**btn_Name**]").trigger('click');
});

Replace btn_Name with the name of the custom button you just created. Now, to make this code run on Page Load, we have to encode it into Base64, and add it to the REQUIRESCRIPT tag.

Use the URL http://rot47.net/base64encoder.html to encode the jQuery code above. This will produce the below result.

dmFyIGokID0galF1ZXJ5Lm5vQ29uZmxpY3QoKTsKaiQoZG9jdW1lbnQpLnJlYWR5KGZ1bmN0aW9uKCl7CmokKCJpbnB1dFtuYW1lPXVwbG9hZF9kb2N1bWVudF0iKS5jc3MoJ2Rpc3BsYXknLCdub25lJyk7CmokKCJpbnB1dFtuYW1lPXVwbG9hZF9kb2N1bWVudF0iKS50cmlnZ2VyKCdjbGljaycpOwp9KTs=

We then use the below statement to embed this encoded content :

{!REQUIRESCRIPT('data:application/javascript;base64,**ENCODED STRING**')}

After this, you can write the Javascript code you want to execute on Load.

The below example displays an alert on page load.

{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js')}
{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js')}
{!REQUIRESCRIPT('data:application/javascript;base64,dmFyIGokID0galF1ZXJ5Lm5vQ29uZmxpY3QoKTsKaiQoZG9jdW1lbnQpLnJlYWR5KGZ1bmN0aW9uKCl7CmokKCJpbnB1dFtuYW1lPXVwbG9hZF9kb2N1bWVudF0iKS5jc3MoJ2Rpc3BsYXknLCdub25lJyk7CmokKCJpbnB1dFtuYW1lPXVwbG9hZF9kb2N1bWVudF0iKS50cmlnZ2VyKCdjbGljaycpOwp9KTs=')}
alert('Hi {!$User.FirstName}');

Since, the custom button is present in the HTML Content of the Object Detail page, you can use jQuery to select any element of the entire page and customize it.

This will work in all places where SF Buttons are shown. So it won't work in Salesforce1.