https://www.growthbook.io/ logo
#ask-questions
Title
# ask-questions
b

busy-air-96466

03/27/2023, 7:04 PM
Hiya, I am trying to use Puppeteer to auto-generate data for my GrowthBook demo. My puppeteer script appears to work perfectly but none of the GA events (defined with GTM) are firing, except the initial page_view. I’ve googled but can’t find any reason why the GA events would work when I visit the page and perform actions manually, but not when Puppeteer does the same thing? I’m running a React app locally on port 3000, and GrowthBook locally on port 4000. GA events from Puppeteer are not showing up in BigQuery, and when I intercept requests, it appears that they are not being sent. Forgive me if this question is too out-of-scope; I realise there’s no fault in GrowthBook, I’m just out of ideas! Here’s my Puppeteer script:
Copy code
const puppeteer = require('puppeteer');
const seedrandom = require('seedrandom');

const mainCTAProbabilities = {
  freeControl: 0.3,
  freeExperiment: 0.5,
  paidControl: 0.6,
  paidExperiment: 0.7,
};

const requestUrlParamsToJSON = requestURL => {
  // Split request parameters and store as key-value object for easy access
  let params = requestURL.split('?')[1];
  return JSON.parse(
    '{"' +
      decodeURI(params)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}',
  );
};

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  page
    .on('console', message =>
      console.log(
        `${message.type().substr(0, 3).toUpperCase()} ${message.text()}`,
      ),
    )
    .on('pageerror', ({ message }) => console.log(message))
    .on('response', response =>
      console.log(`${response.status()} ${response.url()}`),
    )
    .on('requestfailed', request =>
      console.log(`${request.failure().errorText} ${request.url()}`),
    );

  await page.setRequestInterception(true);
  page.on('request', req => {
    const requestURL = req.url();
    console.log('all url', requestURL);
    if (requestURL.indexOf('<http://google-analytics.com/g/collect|google-analytics.com/g/collect>') > -1) {
      console.log('Intercepted: ' + requestURL);
      console.log('full req', requestUrlParamsToJSON(requestURL));
      //req.abort();
      req.continue();
    } else {
      req.continue();
    }
  });

  await page.goto('<http://localhost:3000/>');

  // Set screen size
  await page.setViewport({ width: 1080, height: 1024 });

  let userCount = 1;

  const accountType = 'free';

  const username = `${accountType}-puppeteer-${userCount}`;

  // Enter username
  await page.type('.username-input', username);

  // Click login button
  const loginButton = '.login-button';
  await page.waitForSelector(loginButton);
  await page.click(loginButton);

  // Locate the main panel and read the title
  console.log('logged in as', username);
  const textSelector = await page.waitForSelector('.main-panel h2');
  const panelTitle = await textSelector.evaluate(el => el.textContent);

  // Print the full title
  console.log('The panel title is "%s".', panelTitle);

  // Decide whether to click the Main CTA button
  // use a seeded random number generator to ensure the same user always makes the same decision
  const encounterType =
    panelTitle === 'Welcome (control)' ? 'Control' : 'Experiment';
  const key = `${accountType}${encounterType}`;

  const seededRandomNumberGenerator = seedrandom(username);
  console.log('Key', key, mainCTAProbabilities[key]);
  const dieRoll = seededRandomNumberGenerator();
  const rollToClickCTA = dieRoll >= mainCTAProbabilities[key];
  console.log('die roll', dieRoll);
  if (rollToClickCTA) {
    console.log('gonna click it');
    const mainCTAButton = '#main-cta-button';
    await page.waitForSelector(mainCTAButton);
    await page.click(mainCTAButton);
    console.log('clicked it!');
  } else {
    console.log('nah');
  }

  // logout
  const logoutButton = '.logout-button';
  await page.waitForSelector(logoutButton);
  await page.click(logoutButton);

  await browser.close();
})();
From the console output I can see that the dummy user logs in, and clicks the button. But no GA event is sent. But if I visit the page, login and click the button, the GA event is sent and shows up in BigQuery moments later. Does anyone have any experience of using Puppeteer with Google Tag Manager? Any idea why it’d be different in Headless Chrome? Many thanks for any ideas how to explore this problem!
Apologies again for the off-topic post, but in case anyone else experiences something similar, it seems to work if you set Puppeteer to run headed not headless.
8 Views