I was asked recently about the best way to track a widget, loaded in an iframe, on a third-party site with Google Analytics.
The difficulty is that many browsers now block 3rd party cookies (those set by a different domain to the one in the browser address bar) – and this applies to a Google Analytics cookie for widgets as much as to adverts.
The best solution seems to be to use local storage on the browser (also called HTML5 Storage) to store a persistent identifier for Analytics and bypass the need to set a cookie – but then you have to manually create a clientID to send to Google Analytics.
However, as their comment on line 41 says, this is not a complete solution – because there are lots of browsers beyond Safari which block third party cookies.
I would take the opposite approach and check if the browser supports local storage, and only revert to trying to set a cookie if it does not. Local storage is now possible on 90% of browsers in use and the browsers with worst 3rd party cookie support (Firefox and Safari) luckily have the longest support for local storage.
As a final note, I would set up the tracking on a different Google Analytics property to your main site, so that pageviews of widgets are not confused with pageviews of your main site.
To do list:
- Build a script to create a valid clientID for each new visitor
- Call ga(‘create) function, setting ‘storage’ : ‘none’, and getting the ‘clientID’ from local storage (or created from new)
- Send a pageview (or event) for every time the widget is loaded. Since the widget page is likely to be the same every time it is embedded, you might want to store the document referrer (the parent page URL) instead
Need help with the details? Get in touch with our team of experts and we’d be happy to help!