Google Optimize JS API On SPA
I have a problem with the Google Optimize JS API on my SPA, the callback is only run on page reload but when navigating back and forward to the specific page, the callback isn't being run. Here's the scenario:
1) I reload the application and go to my page having an active A/B-test: mysite.com/testpage
2) The folowing code is being run:
gtag('event', 'optimize.callback', {
name: experimentId,
callback: useVariant,
});
and useVariant(variantId)
is being called setting the correct variantId.
3) I click or navigate away from the page and then click/navigate back to mysite.com/testpage, this is a SPA mind you.
4) The gtag()
code is being re-called, BUT the callback useVariant()
isn't being run.
5) WTF.
6) If I reload the page, using CMD+R (yes, I'm using Mac), the code runs as in point 1) And everything is ok.
I have tried the following:
A. Resetting the datalayer using google_tag_manager['xxx'].datalayer.reset()
B. Re-pushing the event with undefined callback gtag('event', 'optimize.callback', undefined)
C. Resetting datalayer = [] manually
D. Removing the optimize.callback
event from the datalayer
E. Any combination of above (which gives a bit interesting results sometime)
So the question is in point 5: WTF? Any suggestions/thoughts are greatly appreciated.
Thanks!
Answer
I finally solved it! Here's how to fix it, maybe this will help someone else.
The problem is the callback function useVariant
. I had defined it as so useVariant(variantId)
when apperantly (thanks Google documentation for being clear on this, NOT) it has to be useVariant(variantId, experimentId)
So by changing the callback function to take two arguments the code will work.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM