Most companies use Google Analytics or similar web tracking tool to better understand their visitors and how they use the website. These metrics can help you improve your site’s design. Do you ever wonder how your Salesforce users actually use your Salesforce website? Which pages do they visit? Which links do they click? Do they really use that nifty visualforce page you just deployed? How are they navigating Salesforce so that you can improve their user experience? Just as you gather these metrics on your company site, you can do the same by integrating Google Analytics to your Salesforce instance! This solution relies heavily on the “embed javascript via custom home page sidebar component” design by Uwe Heim. It is very easy to put together, setup time approx. 10-15 minutes.
UPDATE (June 2016):
In the comments, Sandeep Kondapalli recommends implementing this solution with Visualforce Home Page component as you can use <apex:includeScript> or native <script> to include the javascript and execute immediately. I have not tried this yet, but hopefully this is the simple change needed to get the solution to work post Winter ’16 release.
UPDATE (October 2015):
As of the Winter ’16 release, custom JavaScript buttons and links no longer have their REQUIRESCRIPT tags executed on page load. Only when the user clicks the button or link will the script be included. This behavior change may render this Google Analytics solution obsolete.
Create Google Analytics Account (FREE)
1. Create your free account at http://www.google.com/analytics/
You will either need to sign-in with existing Google profile or create a new one. I created a new Google profile just for this purpose to not muck with my personal email account.
This was my first foray into Google Analytics and took me a minute to understand how to set it up. Right or wrong, I named my “Account” as my company then created two (2) “Properties”, one for my production salesforce org and one for my sandbox org. This way I could keep clicks in the sandbox environment separate from the real site.
2. Create a new Property to generate a tracking id. You will need to specify a Name and URL for the property. Make sure when specifying the URL you use https:// protocol. The URL should be the base domain you use to log into Salesforce (e.g. https://<yourdomain>.my.salesforce.com or https://<yourserver>.salesforce.com)
As noted above, I actually created two properties, one named “Salesforce Production” and the other “Salesforce Sandbox”.
3. As personal preference, if you scroll down on that same Property Settings page then under the In-Page Analytics section you can enable the Use enhanced link attribution. Because of this, you’ll notice some extra javascript I had to include when we move on to the next step of creating the static resource for Salesforce. 4. And because Salesforce loads standard content and visualforce content on different sub-domains, I also enabled cross-domain tracking, which is a couple more lines of javascript we’ll see in the next step.
Create Static Resource
1. We need to create a javascript file with your GA tracking code. We will upload this file as a Static Resource then reference it on all pages via custom home page sidebar component. Copy and paste the below gist into a file on your computer named GoogleAnalytics.js then replace the UA-xxx on line 16 with your GA tracking code and replace YOURDOMAIN on line 21 with your My Domain prefix. If you haven’t configured in Salesforce a custom domain, you might be able to just use your server instance (e.g. NA8 or CS7). Note, do not include or tags!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hide sidebar component that embedded this javascript | |
$("h2:contains('Google Analytics')").parent().parent().hide(); | |
// Google Universal Analytics (provided by google) | |
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ | |
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), | |
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) | |
})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); | |
// Our analytics tracking id for salesforce production. | |
// We also enabled cross-domain linking plugins to try | |
// and handle that salesforce uses multiple sub-domains | |
// to render standard and visualforce content; we don't | |
// want the bounce arounds to be treated as separate "users" | |
// in the analytics reporting. | |
ga('create', 'UA-xxx', 'auto', { | |
'allowLinker': true | |
}); | |
ga('require', 'linkid', 'linkid.js'); | |
ga('require', 'linker'); | |
ga('linker:autoLink', [/YOURDOMAIN(\.|—)(.)*\.(salesforce|force)\.com/]); | |
ga('send', 'pageview'); |
2. Next we need to upload the file to Salesforce, go to Setup | Develop | Static Resources
3. Click New button
4. Name the resource GoogleAnalytics (one word, no spaces)
5. Click Browse… button and select the javascript file you just created
6. Set Cache Control to Public (read more about cache control)
7. Click Save button
8. Now, due to Salesforce limitation that Custom Link Home Page components do not have access to the $Resource merge field, we need to know the actual URL to the javascript file you uploaded. Click the View file link on the Static Resource page and copy just the relative path like /resource/1408249099000/GoogleAnalytics.js. That number is actually a date timestamp that Salesforce uses for caching purposes.
Create Home Page Custom Link
1. Now we need to create a custom link to display in the sidebar that will load our Google Analytics resource so that tracking runs on every page. Go to Setup | Customize | Home | Custom Links
2. Click New button
3. Label it Google Analytics (this can have spaces)
4. Change Behavior to Execute JavaScript
5. Change Content Source to OnClick JavaScript (don’t worry, our solution doesn’t rely on user clicking this custom link)
6. Copy and paste these two lines into the body of the custom link then replace the two red highlighted sections as appropriate. You’ll notice all we’re doing is including other javascript files via the {!REQUIRESCRIPT(..)} function, this is why the trick works immediately without the user have to actually “click” on this Custom Link – the scripts will be loaded when page loads. Also note, I’m including jQuery so that I can use it to hide the sidebar component that will contain this Custom Link (which is the first line of code in the GoogleAnalytics.js file)
{!REQUIRESCRIPT("//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js")}
{!REQUIRESCRIPT("/resource/1408255708000/GoogleAnalytics")}
7. Click Save button
Create Home Page Component
1. Go to Setup | Customize | Home | Home Page Components
2. Click New button
3. If prompted with overview page, click Next button
4. Name the component Google Analytics (this is two words)
5. Change Type to be Links
6. Click Next button
7. Choose your Google_Analytics link from the left list of options and move it to the right as the custom link to show in this new home page component
8. Click Save button
9. Next we need to actually add this home page component to a Home Page Layout(s) assigned to users we want to track. I recommend adding it to all layouts you use. Go to Setup | Customize | Home | Home Page Layouts
10. Click Edit button next to the layout you want to add the Google Analytics tracking to
11. Check the box next to Google Analytics
12. Click Next button
13. Click Save button
Show Custom Sidebar Components on All Pages
1. Last but not least, go to Setup | Customize | User Interface
2. Ensure the sidebar option “Show Custom Sidebar Components on All Pages” is checked
Hi Doug, I really like this post. I’ve went step by step though your guide but I don’t get any data for my Remedyforce users. Is there a place you can help me with this?
LikeLike
Hi Wayne, thanks for the positive feedback. Do you have any idea which step you might be having a problem with? Can you verify that you’re using your analytics tracking id and not a copy & paste error from my examples? You also may want to ensure any single or double quotes aren’t “special characters” and are exactly as would be if you were to literally type then in from your keyboard. Sometimes the blog post uses different font, or when copying from another program the characters change.
LikeLike
Hi Doug, I really like this post as i feel this is an excellent answer but I went step by step though your guide but I got nothing, basically i’m manipulating system predefined div tags (i.e. disabling/hiding css divs), do you have a space you can help me with this?
LikeLike
Never Mind Doug, I got this in a different way .. Thanks!
LikeLike
Hi Satish,
Thank you for your warm feedback! Can you elaborate what issue you were having and what workaround you implemented? The “hiding” part of the code relies on jquery. The jquery library is included into the page by the home page component using the ‘requirescript’ function.
Doug
LikeLike
Hi Doug,
I have a question about Step 1, where you instruct to enter your “My Domain” prefix on line 21.
I am creating the analytics site for my sandbox. Let’s pretend my sandbox is named “Dev1” for the “Acme” company.
The “My Domain” looks like this: Acme–Dev1.cs06.my.salesforce.com.
My question is, which code piece is correct, A or B?
Option A: ga(‘linker:autoLink’, [/Acme(\.|–)(.)*\.(salesforce|force)\.com/]);
Option B: ga(‘linker:autoLink’, [/Acme–Dev1(\.|–)(.)*\.(salesforce|force)\.com/]);
Thanks for you help and for a great post!
JD
LikeLiked by 1 person
As you noted in a later comment, option A would already match the –dev1 (or whatever your sandbox name is)
LikeLike
Also, in step 6 on the first line of REQUIRESCRIPT, you list JQuery 2.1.1. I believe the current version is 2.1.4. Can I use 2.1.1 or does it matter which version I load there?
Thanks!
JD
LikeLike
You can use whichever version. At the time, I beleive 2.1.1 was the latest.
LikeLike
Hi Doug,
I figured this out! I didnt realize the the reg exp included the “or” to account for the “–” after my domain. I might have been a little antsy just before the holiday break! 😉 Looks like this is up now. I would like to point out to other users to make sure to follow your advice in step 2; “Make sure when specifying the URL you use https:// protocol.” I failed to do this and it wont work properly without it.
Another cool tip is to try the Google Analytics Page View extension for chrome. Check it out here:
https://chrome.google.com/webstore/detail/page-analytics-by-google/fnbdnhhicmebfgdgglcdacdapkcihcoh?utm_source=gmail
Thanks again for such a great post!
JD
LikeLiked by 1 person
Hi Doug … I have implemented this on my Partner Portal.
The Link is not loading the files itself, I have to click the link than the JS files are loaded.. after clicking on it the Google Analytics Link disappears and the Analytics.js is executed…. What am I doing wrong that it is not working on its own…
Further {!REQUIRESCRIPT(“/resource/1408255708000/GoogleAnalytics”)} is not working, I have to provide whole link for the Resource, directly referencing is taking the initial URL of Partner Portal not my Org where I have uploaded my doc.
LikeLiked by 1 person
Hi Vishal,
As of the Winter ’16 release, custom JavaScript buttons and links no longer have their REQUIRESCRIPT tags executed on page load. Only when the user clicks the button or link will the script be included, as you’ve noticed. This behavior change may render this Google Analytics solution obsolete as it relied entirely on the old behavior where the script was executed automatically on page load. So, I wouldn’t say you’re doing anything wrong if you’re copying this approach, but rather that Salesforce has recently changed their implementation of REQUIRESCRIPT that now requires developers to seek out alternative solutions.
The second issue you mentioned about the relative path to the Google Analytics resource not resolving correctly when in the Portal I believe is due to Portals being served up in in a different directory than the normal internal instance. This actually causes visualforce developers a lot of grief when trying to reuse pages for internal and external communities because they have to build the URL’s differently depending on where the page is being served up. You might want to try prefixing your URL’s with $Site.prefix variable as outlined on the developer forums: https://developer.salesforce.com/forums/?id=906F000000099IfIAI
Best of luck!
Doug
LikeLike
Hi Doug, Thank you for the insights/solution provided here. As you have said Winter 16 made the javascript solution obselete and doesn’t work. However, it helped me come up with a new solution where I just embedded the javascript in a VF page, created a visual force narrow homepage component and put that on the pagelayout. This helped and I am now able to report on the analytics being passed over to google.
Thanks again for your insights and solution.
LikeLiked by 1 person
That’s great to hear Sandeep! Thanks for sharing your update! I will definitely try the visualforce homepage component to see if that works for me too.
LikeLike
Hi sandeep, Could you please elaborate on what you did as a fix as compared to earlier javascript solution like- what to add in the VF page, where to refer that VF page etc.
Thanks in advance
LikeLike
Hey Rohith, Here is what I did
Create a VF page (details below)
Create a New VF homepage component
Add the homepage component to a HomePage Layout.
// hide sidebar component that embedded this javascript
//”h2:contains(‘Google Analytics’)”).parent().parent().hide();
// Google Universal Analytics (provided by google)
(function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,’script’,’//www.google-analytics.com/analytics.js’,’ga’);
// GA ID provided would be just the ID provided to you when you setup google analytics account for your org.
ga(‘create’, ‘GA ID’, ‘auto’, {
‘allowLinker’: true
});
ga(‘require’, ‘linkid’, ‘linkid.js’);
ga(‘require’, ‘linker’);
ga(‘linker:autoLink’, [/<**your customdomain>(.|–)(.).(salesforce|force).com/]);
ga(‘send’, ‘pageview’);
LikeLike
Did that work out for you Doug – Visualforce Home Page component?
LikeLiked by 1 person
Hi Mike, I have not tried it yet.
LikeLike
@Sandeep, @Doug Ayers
I have question here.I also work with integrating visualforce with GA and this VF is internal , not Site enabled. I followed instruction in Google which is not to similar with Google Universal above.I just paste the script in VF and in GA account I can see it tracking.Now after I reading this, I wondering what the different between GA Universal script above and the one that I paste in my header?Is it because this is Homepage?
Just sample of the script that I paste in the header.
https://www.googletagmanager.com/gtag/js?id=UA-xxxxxx-x
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag(‘js’, new Date());
gtag(‘config’, ‘UA-xxxxxx-x’);
LikeLike
@unid,
The above code I paste in the VF page like below. But it is not tracking in GA account. Could you please help me as it is urgent requirement for me.
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag(‘js’, new Date());
Regards,
Md. Saddam
LikeLike