How to (Actually) Install Google Tag Manager on Google Sites

Install GTM on Google Sites

Here's the code for your Cloudflare Worker.

Important: You will need to change GTM-CONTAINER to your Google Tag Manager container ID.

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const response = await fetch(request);
  const contentType = response.headers.get('content-type') || '';

  if (!contentType.includes('text/html')) {
    return response;
  }

  const newResponse = new HTMLRewriter()
    .on('head', new HeadHandler())
    .transform(response);

  const modifiedResponse = new Response(newResponse.body, newResponse);
  modifiedResponse.headers.delete('Content-Security-Policy');

  return modifiedResponse;
}

class HeadHandler {
  element(element) {
    element.prepend(`
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-CONTAINER');</script>
<!-- End Google Tag Manager -->`, { html: true });
  }
}

This article was updated on 25 March 2026