[go: up one dir, main page]

Quickstart: Google Analytics

Quickstart with Google Analytics

Since Manifest V3 does not support remote code execution (opens in a new tab), it has been very difficult for developers to integrate Google Analytics into their extension project, especially with the latest gtag4 version (opens in a new tab).

To overcome this issue, Plasmo bundles remote code at build time.

Obtaining the Tracking/Measurement ID

You will first need to create a property to get the Tracking ID. During this process, Google will ask to provide a website URL - we suggest providing a subdomain of your domain. This ensures the data coming in is only from your properties - website/domain/extension.

♻️

You can reuse any property you own (for example, the website property you use to market your extension).

Then, to get the Measurement ID, visit your Google Analytics dashboard, and navigate to the Tagging Instructions section (Admin -> Setup Assistant -> Tag installation -> Data Streams -> Web):

Measurement ID

Click the button next to the Measurement ID, which should copy to your clipboard.

Env Variable Setup

To properly store the Measurement ID, we recommend using environment variables. Create an .env.local file:

.env.local
PLASMO_PUBLIC_GTAG_ID=<paste in your measurement ID>

To get TypeScript IntelliSense, create an index.d.ts file:

index.d.ts
declare namespace NodeJS {
  interface ProcessEnv {
    PLASMO_PUBLIC_GTAG_ID?: string
  }
}
 
interface Window {
  dataLayer: Array
  gtag: (a: string, b: any, c?: any) => void
}

Using Google Analytics in a React component

Below is an example of how to implement the google tag tracking script in the popup page:

popup.tsx
import "https://www.googletagmanager.com/gtag/js?id=$PLASMO_PUBLIC_GTAG_ID"
 
import { useEffect, useState } from "react"
 
function IndexPopup() {
  const [data, setData] = useState("")
 
  useEffect(() => {
    window.dataLayer = window.dataLayer || []
    window.gtag = function gtag() {
      window.dataLayer.push(arguments) // eslint-disable-line
    }
    window.gtag("js", new Date())
    window.gtag("config", process.env.PLASMO_PUBLIC_GTAG_ID, {
      page_path: "/popup",
      debug_mode: true
    })
 
    window.gtag("event", "login", {
      method: "TEST"
    })
  }, [])
 
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        padding: 16
      }}>
      <h1>
        Welcome to your <a href="https://www.plasmo.com">Plasmo</a> Extension!
      </h1>
      <input onChange={(e) => setData(e.target.value)} value={data} />
    </div>
  )
}
 
export default IndexPopup

The import statement and the code inside the useEffect is identical to what Google gives you (see image below). We adapted them into the React lifecycle. We also add the window object to make it work with Typescript.

Measurement ID

Full Example

To see a complete example, check out with-google-analytics (opens in a new tab) in our examples repo.