Google unveiled a Google ‘Save to Drive’ button for website publishers that allows their users to download files directly into their Google Drive accounts. Although a ‘Save to Drive’ Chrome extension has been around for a while now, this solution is great because not every person is a plugin/extension junkie like some of us.
This caught my attention because at IO we publish whitepapers that we want people to download. This ‘Save to Drive’ button sounded neat, but honestly I had to ask myself… would people even use this feature??
I don’t know. So let’s track it.
I love tracking all sorts of things in Google Analytics. When I looked at the documentation to implement the ‘Save to Drive’ button, however, I realized that there is currently no supported callback function in the API. Meaning, this solution doesn’t give us an explicit/official way to say “Perform this GA event tracking after the button loads”.
Now, I probably should have stopped there and reminded myself that this is a new feature. And that maybe after some time they’ll update the API and add a supported callback function and there would be no need to devote so much time into hacking up some code (after a lot of trial and error) and I should just be patient for a bit.
But I want to track these downloads now. 🙂
So, I began code hacking. And now I want to share it with you.
What exactly are we tracking?
Because of the lack of an official tracking method in the API, we have some serious limitations to deal with. One is that we’re NOT able to track the actual confirmed download of a file. We’re just tracking the click of the button. This is the best I can do.
Teenage MutationObserver Turtles
For you technical folks: The ‘Save to Drive’ button documentation has a few different implementations, all of which add a bit of uncertainty of knowing when the iframe button will load. We needed a smart way to listen to changes in the DOM to see when the iframe is created and THEN attach our jQuery handlers. This is where the MutationObserver API comes in. Also, because we’re dealing with a cross-domain iframe, the browser won’t allow us to attach click handlers for anything inside the iframe. For this, we have to use a trick to detect a hover over the area of the iframe and then a blur once focus is lost in our document. You can learn more about that here.
Here’s the code
‘Save to Drive’ async load + my custom code:
Here’s an example of the button with GA tracking for the SEOmoz Beginner’s Guide to SEO:
There should be a better way
That being said, I hope this gives you a little fun with tracking this new button. Enjoy!