Ad

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!

Ad

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.

Ad
source: stackoverflow.com
Ad