koko-analytics
koko-analytics copied to clipboard
Feature request: Expose trackPageview for setups with Barba.js or similar libraries
Hi there,
Thank you for making this great plugin.
For one website we are using Barba.js that uses Ajax to load the pages. This makes it feel super speedy and you can add hip and nice transitions.
With Koko Analytics I was not able to find a JS function to manually track pageviews. On another website with Barba and with Google Analytics, we are able to use gtag('event', 'page_view', { page_path: location.pathname }); whenever barba is done loading.
Let me know if this request is feasible, if you need more info from me or if there is anyway I can help make it happen.
Thank you!
Hello @joshuadelange,
Koko Analytics doesn't offer any function to manually track a pageview right now, but I can see this being useful. This is complicated by the fact that Koko integrates with WordPress tightly and thus doesn't use pathnames or URL's but post ID's instead. It would also need logic to deal with document.referrer not being reset by Barba.js (since it's a read-only property) so we need to prevent double-recording of the same referrer.
Is there a way to easily get the post ID using Barba.js in combination with WordPress? Parsing the class attribute of the <body> element?
Hi @dannyvankooten,
Thanks for looking into it!
With the Barba + WP integration we already need to do things like updating the body class, meta tags, etc whenever a transition happens. Grabbing the post ID from a data attribute on the body tag or so should be no problem.
Hello @joshuadelange,
A bit late, but after 7bd9d001175521c8549bac4287977bebe60a0a34 this function is now exposed on the global window.koko_analytics object. Here's an example of using it:
window.koko_analytics.trackPageview(0); // to track a visit to the homepage
window.koko_analytics.trackPageview(25); // to track a visit to the post with ID 25
window.koko_analytics.trackPageview(-1); // to track a visit to any other page (eg category archive)
We're including this change in the next plugin release, so version 1.0.35 will have this. :slightly_smiling_face:
To extract a post ID from the <body> element, you can use the following:
let postId = -1 // general site visit
// if this is a visit to a specific page or post, we need to supply the post ID to trackPageview
// so we extract if from the <body> element
const matches = document.body.className.match(/(postid-|page-id-)(\d+)/)
if (matches && matches.length === 3) {
postId = matches.pop()
}
window.koko_analytics.trackPageview(postId)
Just for reference: It is possible to let WordPress resolve a URL to a post id: https://developer.wordpress.org/reference/functions/url_to_postid/
Hello @dannyvankooten , that is great news! Thank you for your work on this.