Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Google Tag Assistant (Google Tag Manager preview) #72

Open
Manduro opened this issue Feb 11, 2022 · 84 comments · Fixed by #573
Open

Support for Google Tag Assistant (Google Tag Manager preview) #72

Manduro opened this issue Feb 11, 2022 · 84 comments · Fixed by #573

Comments

@Manduro
Copy link
Contributor

Manduro commented Feb 11, 2022

When using Google Tag Assistant to test a Proxytown implementation of Google Tag Manager, it fails to connect:
Screenshot 2022-02-11 at 16 01 04
At first there were some CORS errors for the googletagmanager.com domain. After proxying those I can see the iframe getting added to the page, but it fails to load and some Partytown error occurs:

Screenshot 2022-02-11 at 16 07 01

In the page's <head> I can see the following scripts:

<script type="text/partytown-x" src="http://localhost:3003/~partytownproxy/google-analytics/analytics.js" data-ptsrc="https://www.google-analytics.com/analytics.js" data-ptid="351043767"></script>
<script type="text/partytown-x" src="http://localhost:3003/~partytownproxy/googletagmanager/gtag/js" data-ptsrc="http://www.googletagmanager.com/gtag/js?id=G-44K8TKMTS9&amp;l=dataLayer&amp;cx=c" data-ptid="574473788"></script>
<script type="text/partytown" src="http://localhost:3003/~partytownproxy/googletagmanager/debug/bootstrap" data-ptsrc="https://www.googletagmanager.com/debug/bootstrap?id=GTM-XXXXXXX&amp;src=GTM&amp;cond=2&amp;gtm=2wg290" data-ptid="433709864" data-pterror="Error: Error finding instance &quot;1&quot; on window 2 (259405394)
    at sendToMain (http://localhost:3003/~partytown/debug/partytown-ww-sw.js:253:27)
    at queue (http://localhost:3003/~partytown/debug/partytown-ww-sw.js:226:20)
    at callMethod (http://localhost:3003/~partytown/debug/partytown-ww-sw.js:333:20)
    at Node.<anonymous> (http://localhost:3003/~partytown/debug/partytown-ww-sw.js:1338:24)
    at wc (https://www.googletagmanager.com/debug/bootstrap?id=GTM-XXXXXXX&amp;src=GTM&amp;cond=2&amp;gtm=2wg290:53:163)
    at eval (https://www.googletagmanager.com/debug/bootstrap?id=GTM-XXXXXXX&amp;src=GTM&amp;cond=2&amp;gtm=2wg290:66:331)
    at lc (https://www.googletagmanager.com/debug/bootstrap?id=GTM-XXXXXXX&amp;src=GTM&amp;cond=2&amp;gtm=2wg290:47:924)
    at Bc.start (https://www.googletagmanager.com/debug/bootstrap?id=GTM-XXXXXXX&amp;src=GTM&amp;cond=2&amp;gtm=2wg290:65:932)
    at eval (https://www.googletagmanager.com/debug/bootstrap?id=GTM-XXXXXXX&amp;src=GTM&amp;cond=2&amp;gtm=2wg290:70:1364)
    at Proxy.eval (https://www.googletagmanager.com/debug/bootstrap?id=GTM-XXXXXXX&amp;src=GTM&amp;cond=2&amp;gtm=2wg290:77:3)"></script>

And just before the </body>:

<iframe src="about:blank" class="__TAG_ASSISTANT_BADGE" frameborder="0" style="border: 0 !important; bottom: 24px !important; border-radius: 8px !important; box-shadow: 0 3px 5px -1px rgb(0 0 0 / 20%), 0 5px 8px 0 rgb(0 0 0 / 14%), 0 1px 14px 0 rgb(0 0 0 / 12%) !important; clip: initial !important; display: inline !important; height: 200px !important; left: auto !important; margin: 0 !important; max-width: 95% !important; opacity: 1 !important; padding: 0 !important; position: fixed !important; right: 24px !important; top: auto !important; visibility: visible !important; width: 450px !important; z-index: 2147483647 !important;" data-ptwindow="259405394"></iframe>

When switching back to the default GTM implementation (without Partytown), everything works as expected.

@ghost
Copy link

ghost commented Feb 15, 2022

I am having the same issue here. On top of that, I also seem to be getting CORs for google analytics.
image

@Legym
Copy link

Legym commented Feb 15, 2022

I am also loading Google Tag Assistant. However by sheer luck it randomly connected. I kept refreshing and after about 40 times it finally connected. Ive been able to connect 3 times without the error, but it does seem like its completely random. I've been getting OPs original error when it does not connect.

image

image

@Manduro Manduro changed the title Support for Google Tag Assistent Support for Google Tag Assistent (Google Tag Manager preview) Feb 18, 2022
@ghost
Copy link

ghost commented Feb 22, 2022

So the main reason this is happening from my investigation is that when you try to connect google tag assistant to your app, it will try to fetch the script from https://www.googletagmanager.com/debug/bootstrap?cond=2&id=GTM-xxxxxxx which does not have the right headers in place and results in CORs.

This requires a reverse proxy set up for this particular resource and I've set it up a way as shown below:

                <Partytown
                    forward={['dataLayer.push']}
                    resolveUrl={(url) => {
                        if (url.pathname.includes('debug/bootstrap')) {
                            var proxyUrl = new URL(
                                'https://your-hosted-url/party-proxy',
                            )
                            proxyUrl.searchParams.append('url', url)
                            return proxyUrl
                        }
                        return url
                    }}
                />

and I've set up a proxy with NGINX with a hard-coded link for testing purposes as below

    location /party-proxy {
        proxy_set_header Access-Control-Allow-Origin *;
        proxy_pass https://www.googletagmanager.com/debug/bootstrap?id=GTM-xxxxxxx&src=GTM&cond=2;
    }

This helps me get passed the CORs issue but I end up with these errors in the console after the timeout and I can't seem to identify what I may need to forward to the main thread.

image

image

@tarponjargon
Copy link

tarponjargon commented Mar 17, 2022

This helps me get passed the CORs issue but I end up with these errors in the console after the timeout and I can't seem to identify what I may need to forward to the main thread.

Yeah I got to the same point. the c.Postmessage is not a function error is repeated every second.

To make sure it's not a disallowing the POST method I tried adding:

headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "GET,POST,HEAD,OPTIONS";

To my reverse proxy to https://www.googletagmanager.com/debug/bootstrap...
And that doesn't seem to be the issue.

There's a partytown JS error that precedes the postMessage error. I ran partytown in debug mode and here's the console output (in case it's helpful to anybody).

The solution I ultimately arrived at is to set a query param like ?no_partytown=1 that if true, suppresses type="text/partytown" on the gtm script tag.

Screen Shot 2022-03-17 at 3 54 56 PM

@slawekkolodziej
Copy link
Contributor

I played with integrating tag assistant here: https://github.com/slawekkolodziej/partytown/tree/tag-assistant

I wrote a document with what I've found: https://github.com/slawekkolodziej/partytown/blob/tag-assistant/src/lib/web-worker/tag-assistant.md

The implementation is not finished yet. It's rather at early stage / POC. There are some missing parts and the implementation is definitely not production ready.

@graysonhicks
Copy link

Thanks @slawekkolodziej, I think the doc you linked has moved here: https://github.com/slawekkolodziej/partytown/blob/tag-assistant/docs/tag-assistant.md.

Would this issue be causing this behavior?

image

image

Basically added GTM with Partytown but unable to debug that events are working before merging Partytown to production.

@slawekkolodziej
Copy link
Contributor

Hey @graysonhicks yes, I moved that file recently. From your screenshots I can tell that you are using legacy Tag Assistant plugin. My code works with Tag Assistant Companion (https://chrome.google.com/webstore/detail/tag-assistant-companion/jmekfmbnaedfebfnmakmokmlfpblbfdm).

I figured out a nicer way to integrate Tag Assistant that doesn't require adding GTM-specific code to Partytown. However, it still needs some changes in src/lib/web-worker/worker-serialization.ts.

@ryfazrin
Copy link
Contributor

ryfazrin commented Jun 6, 2022

thanks @slawekkolodziej, I found a similar problem in version 6.2. I think you have added this from your PR (#183).

Do I need to follow the steps you share here https://github.com/slawekkolodziej/partytown/blob/tag-assistant/docs/tag-assistant.md ?

@Callan003
Copy link
Contributor

I am facing the same issue.
I am able to move the GTM script to a SW, but once it is there, I am not able to test the GTM events.

Any suggestion on how I should test it?

@franceschiniandrea
Copy link

I read the guide about debugging Tag Assistant, but I'm still confused on a few things:

  1. How do I check whether GTM is running in debug mode?
  2. How do I proxy the request in Gatsby? Do I necessarily need a backend?

@graysonhicks
Copy link

@NotFrancee I'm still not clear either on the debug mode.

For Gatsby the proxy is either with createRedirect if you are not using the Script component or with the partytownProxiedUrls option if you are using the Script component.

Without Script component:
https://github.com/PaulieScanlon/gatsby-third-party-scripts/pull/4/files

With Script component:
https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-script/#proxy-configuration

@babvi
Copy link

babvi commented Jan 5, 2023

I'm also facing the same error
partytown-ww-sw.js?v=0.7.3:1715
Error: Error finding instance "1ycwlf6dz4.d" on window 2

On nextJS 11.
Anyone know how to test / fix this?

@babvi
Copy link

babvi commented Jan 5, 2023

The solution I ultimately arrived at is to set a query param like ?no_partytown=1 that if true, suppresses type="text/partytown" on the gtm script tag.

@tarponjargon how you fixed it? Can you paste is here?

@slawekkolodziej
Copy link
Contributor

Just curious, are you trying to use this within react application? I may wrap the code I created in a react component sometime over the next week or two and release it as npm module.

@gabrielmlinassi
Copy link

@slawekkolodziej if you have a sample of how to use partytown with NextJS, please I'd love to see one. I've tried a lot and never managed to make it work with NextJS Script component worker strategy. It always throws CORS errors. Partytown docs says to use NextJS rewrites as a reverse-proxy but never really understood how to do it. Never found any example either.

@babvi
Copy link

babvi commented Jan 6, 2023

@slawekkolodziej I'm working with Next 11 and able to load all GTM and other 3rd parties which are added inside GTM with worker.
I'm able to see realtime analysis in GA as well with partytown worker, But when doing "Tag Assistant" check its show instance error .
I did added all proxies of all my third-parties on nginx which works good.

@LynxTR
Copy link

LynxTR commented Jan 13, 2023

@babvi If its possible can you share a minimal repo. I am facing same issue and couldnt solve it for few days...

@phongnguyen0601
Copy link

I have faced same issue. But I just resolved this issue by update partytown version from 0.7.1 to 0.7.4 and add below code into Set Hook to disable partytown when using Google Tag Assistant (check debug signal in the URL - gtm_debug) in NextJS Static Web:

set={(opts) => { const isDebugging = opts.window.location.search.includes("gtm_debug"); if ( isDebugging && opts.name === "type" && opts.nodeName === "SCRIPT" ) { return opts.prevent; } return opts.continue; }}

@StoraH
Copy link

StoraH commented Jan 16, 2023

@phongnguyen0601 We came up with a similar solution for our SSR (not using NEXT) and it's an okay workaround for the moment.

 function checkIfGoogleTagAssistantIsEnabled(ctx) {
	const [, query] = ctx.request.url.split('?');
	const searchParams = new URLSearchParams(query);

	return !!searchParams.get('gtm_debug');
}

return `<script type="text/${
		checkIfGoogleTagAssistantIsEnabled(ctx) ? 'javascript' : 'partytown'
	}">(function(w,d,s,l,i){w[l]=w[l]||[];w[l].p..........

@SujayPrabhu96
Copy link

This is how I fixed the CORS error for analytics and preview mode

Use resolveUrl in gatsby-ssr.js:

<script
    key="partytown-vanilla-config"
    dangerouslySetInnerHTML={{
       __html: `partytown = {
          resolveUrl(url, location) {
           if (
            url.hostname === "www.google-analytics.com" &&
            url.pathname.endsWith(".js")
           ) {
             var proxyUrl = new URL(location.origin+'/google-analytics');
             proxyUrl.searchParams.append("url", url.href);
             return proxyUrl;
          }
          if (
            url.pathname.includes("/debug/bootstrap")
          ) {
            var proxyUrl = new URL(location.origin+'/googletagmanager/debug/bootstrap');
            proxyUrl.searchParams.append("url", url.href);
            return proxyUrl;
          }
          return url;
         }
       }`,
    }}
 />,

createRedirect in gatsby-node.js

exports.onPreBuild = async ({ actions: { createRedirect } }: any) => {
  await copyLibFiles(path.join(__dirname, "static", "~partytown"));

  createRedirect({
    fromPath: `/google-analytics?url=:url`,
    toPath: `:url`,
    statusCode: 200,
  });

  createRedirect({
    fromPath: `/googletagmanager/debug/bootstrap?url=:url`,
    toPath: `:url`,
    statusCode: 200,
  });
};

@NavidGoalpure
Copy link

@slawekkolodziej if you have a sample of how to use partytown with NextJS, please I'd love to see one. I've tried a lot and never managed to make it work with NextJS Script component worker strategy. It always throws CORS errors. Partytown docs says to use NextJS rewrites as a reverse-proxy but never really understood how to do it. Never found any example either.

If you are looking for a solution, you can take a look at the configuration in my last project. you must put related codes to _app and _document

https://github.com/NavidGoalpure/visabox/blob/master/pages/_document.tsx
https://github.com/NavidGoalpure/visabox/blob/master/pages/_app.tsx

I found this solution on the Internet of course, but I can remember the reference.

@NavidGoalpure
Copy link

NavidGoalpure commented Jan 31, 2023

I have faced same issue. But I just resolved this issue by update partytown version from 0.7.1 to 0.7.4 and add below code into Set Hook to disable partytown when using Google Tag Assistant (check debug signal in the URL - gtm_debug) in NextJS Static Web:

set={(opts) => { const isDebugging = opts.window.location.search.includes("gtm_debug"); if ( isDebugging && opts.name === "type" && opts.nodeName === "SCRIPT" ) { return opts.prevent; } return opts.continue; }}

It works for me! thanks

@phongnguyen0601
Copy link

phongnguyen0601 commented Feb 1, 2023

I have faced same issue. But I just resolved this issue by update partytown version from 0.7.1 to 0.7.4 and add below code into Set Hook to disable partytown when using Google Tag Assistant (check debug signal in the URL - gtm_debug) in NextJS Static Web:

set={(opts) => { const isDebugging = opts.window.location.search.includes("gtm_debug"); if ( isDebugging && opts.name === "type" && opts.nodeName === "SCRIPT" ) { return opts.prevent; } return opts.continue; }}

You can try another way to disable partytown by checking attribute data-tag-assistant-present of document element (#document) inside iframe of partytown sandbox service worker. It works for me:

let docElement = opts.window.document.documentElement;
let assistant = docElement.getAttribute("data-tag-assistant-present");

if (assistant && opts.name === "type" && opts.nodeName === "SCRIPT") {
     return opts.prevent;
}

@carlosananias
Copy link

@phongnguyen0601 We came up with a similar solution for our SSR (not using NEXT) and it's an okay workaround for the moment.

 function checkIfGoogleTagAssistantIsEnabled(ctx) {
	const [, query] = ctx.request.url.split('?');
	const searchParams = new URLSearchParams(query);

	return !!searchParams.get('gtm_debug');
}

return `<script type="text/${
		checkIfGoogleTagAssistantIsEnabled(ctx) ? 'javascript' : 'partytown'
	}">(function(w,d,s,l,i){w[l]=w[l]||[];w[l].p..........

this is great!! very useful!! thanks @phongnguyen0601

@excelsior091224
Copy link

I have same issue.
I'm using @astrojs/partytown.
image
image

@multiplehats
Copy link

Here's how I'm solving this in SvelteKit (not the most dry, but you barely touch this anyway).

//+layout.server.ts
import type { LayoutServerLoad } from './$types';

export const load = (async (event) => {
	const { url } = event;
	const gtmDebug = url.searchParams.get('gtm_debug');

	return {
		gtmDebug: !!gtmDebug
	};
}) satisfies LayoutServerLoad;
<script lang="ts">
	import type { LayoutData } from './$types';
	import { partytownSnippet } from '@builder.io/partytown/integration';
	import { onMount } from 'svelte';
	import { VERCEL_PROD } from '$lib/shared/utils/environment';

	export let data: LayoutData;
	$: ({ gtmDebug } = data);

	let scriptEl: HTMLScriptElement | null = null;

	onMount(() => {
		if (scriptEl) {
			scriptEl.textContent = partytownSnippet();
		}
	});
</script>

<svelte:head>
	{#if VERCEL_PROD}
		<script>
			partytown = {
				forward: ['dataLayer.push'],
				resolveUrl: (url) => {
					const siteUrl = 'https://nocode.gallery/fissa';
					if (url.hostname === 'www.googletagmanager.com') {
						const proxyUrl = new URL(`${siteUrl}/gtm`);

						const gtmId = new URL(url).searchParams.get('id');
						gtmId && proxyUrl.searchParams.append('id', gtmId);

						return proxyUrl;
					} else if (url.hostname === 'www.google-analytics.com') {
						const proxyUrl = new URL(`${siteUrl}/ga`);

						return proxyUrl;
					}
					return url;
				}
			};
		</script>

		<script bind:this={scriptEl}></script>

		{#if gtmDebug}
			<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-XXX');
			</script>
		{:else}
			<script type="text/partytown">
				(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-XXX');
			</script>
		{/if}
	{/if}
</svelte:head>

<slot />

@marcowuethrich
Copy link

@gioboa Not a public repository but our company landing page uses this implementation find-ida.com. If you have any specify question about it let me know.

@gioboa
Copy link
Collaborator

gioboa commented Nov 19, 2023

@gioboa Not a public repository but our company landing page uses this implementation find-ida.com. If you have any specify question about it let me know.

That's nice, would you like to add your website here? #497
Thanks for sharing.

@sthobis
Copy link

sthobis commented Nov 20, 2023

@marcowuethrich
In my opinion disabling partytown by using text/javascript instead of text/partytown is not an ideal solution as it doesn't reflect actual production usage. Thanks for sharing though.

I put together my solution in a npm module some time ago. You can check it out here: @superside-oss/partytown-gtm.

There are some things that are still not perfect, but it works okay for us.

I tried replicating this but I got this error #202
Do you have some clue on what might be causing this @slawekkolodziej

@slawekkolodziej
Copy link
Contributor

@sthobis I did not face that specific issue.

By "There are some things that are still not perfect, but it works okay for us" I meant two things:
a) TagAssistant banner does not load properly. It shows transparent window with that shadow / border. Exactly what I can see in the screenshot in your post).
b) I only implemented API for Tag Assistant browser plugin. If the plugin is missing, my approach won't work.

However there are 3 main parts that needs to be taken care of:

  1. Tag Assistant browser plugin (this adds GTM-specific APIs to the window object)
  2. Code that runs in main thread AND worker to work as a communication channel between GTM and that plugin-specific browser API.
  3. Proxying some GTM-specific JS files as they are missing proper CORS headers

@yurasytnyk
Copy link

yurasytnyk commented Dec 6, 2023

this is what worked for me in Next.js pages router (_document.tsx) sorry for the bad text formatting

import { Partytown } from "@builder.io/partytown/react";
import { Html, Head, Main, NextScript } from "next/document";

export default function Document() {
  return (
    <Html lang="en">
      <Head>
        <Partytown
          debug={true}
          forward={["dataLayer.push"]}
          set={(opts) => {
            const isDebugging = opts?.window?.location?.search.includes("gtm_debug");

            if (isDebugging && opts?.name === "type" && opts?.nodeName === "SCRIPT") {
              return opts.prevent;
            }

            return opts.continue;
          }}
        />

        <script
          id="gtm"
          type="text/partytown"
          dangerouslySetInnerHTML={{
            __html: `(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-id');`,
          }}
        />
      </Head>

      <body>
        <Main />
        <NextScript />

        <noscript>
          <iframe
            src="https://www.googletagmanager.com/ns.html?id=GTM-id"
            height="0"
            width="0"
            className="hidden"
          ></iframe>
        </noscript>
      </body>
    </Html>
  );
}

@geekysaurabh001
Copy link

this is what worked for me in Next.js pages router (_document.tsx) sorry for the bad text formatting

import { Partytown } from "@builder.io/partytown/react";
import { Html, Head, Main, NextScript } from "next/document";

export default function Document() {
  return (
    <Html lang="en">
      <Head>
        <Partytown
          debug={true}
          forward={["dataLayer.push"]}
          set={(opts) => {
            const isDebugging = opts?.window?.location?.search.includes("gtm_debug");

            if (isDebugging && opts?.name === "type" && opts?.nodeName === "SCRIPT") {
              return opts.prevent;
            }

            return opts.continue;
          }}
        />

        <script
          id="gtm"
          type="text/partytown"
          dangerouslySetInnerHTML={{
            __html: `(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-id');`,
          }}
        />
      </Head>

      <body>
        <Main />
        <NextScript />

        <noscript>
          <iframe
            src="https://www.googletagmanager.com/ns.html?id=GTM-id"
            height="0"
            width="0"
            className="hidden"
          ></iframe>
        </noscript>
      </body>
    </Html>
  );
}

Can we test using Preview mode via this method?

@yurasytnyk
Copy link

yes you can, I tested it yesterday

@geekysaurabh001
Copy link

yes you can, I tested it yesterday

Doesn't work. Same CORS issue is present again.

@yurasytnyk
Copy link

@geekysaurabh001 did you publish your GTM container? It can cause problems with CORS if not published

@callum-gander
Copy link

callum-gander commented Feb 8, 2024

Is there any progress on this?

It feels like a pretty big oversight that scripts like GTM are arguably the biggest and most widely used use case for PartyTown yet the issue of how to run them in PartyTown and debug/preview with Google Tag Assistant isn't properly supported.

A lot of the above solutions seem to basically be "don't run the script with PT when you're debugging" but we can't just assume that everything that works perfectly in the main thread is going to work correctly in the PT worker, as @sthobis has more or less said.

@slawekkolodziej's solution here seems to be a step towards trying to resolve this but has been sitting in this thread for over a year without proper investigation by the maintainers and integration of it into the codebase + docs as a recommendation.

This library attempts to solve a really important problem for a lot of websites and it's great that it trying to. However, the DX is really poor and makes it a massive risk integrating for companies for whom GTM and 3P scripts have important roles in their business.

I really would like to use this library, but the fact that it's been around for 3 years and it's still in beta with issues like this outstanding for over a year makes it really, really difficult, as it just feels wildly under maintained at this point. It makes it hard to persuade the other people on my team that this is something we should use, even if we do definitely need it due to the impact of 3P scripts on the main thread

@gioboa
Copy link
Collaborator

gioboa commented Feb 8, 2024

@callum-gander what's your stack? There are a lot of different errors in this thread. Which is yours?

@callum-gander
Copy link

callum-gander commented Feb 8, 2024

Next.js 14, PT is successfully loading GTM but Google Tag Assistant can't connect to it on http://localhost:3000, presuming because GTM is running in the service worker, any up to date advice on handling this?

Thanks for the fast response btw

Screenshot 2024-02-08 at 12 06 44

@gioboa
Copy link
Collaborator

gioboa commented Feb 8, 2024

You can take inspiration from @marcowuethrich code, he added a specific check in his angular application. Here is the code
@callum-gander Did you already try did approach?

@callum-gander
Copy link

Correct me if I'm wrong, but that solution is the type of solution I said isn't optimal in my previous message.

All that's doing seems to be switching the type="text/partytown" to type="text/javascript" on the GTM scripts when gtm_debug is present in the URL. This isn't ideal as that's just testing whether events are all working on the main thread, which we can assume they are, what we want to test is whether they're still all coming through when GTM is running in the PT worker, which we can't assume before pushing to production. We need to be able to robustly test that everything is working correctly with the partytown worker before we push to production as it can mess up all sorts of experiments that we're running.

This seems to be possible from @slawekkolodziej's work here https://github.com/slawekkolodziej/partytown/blob/tag-assistant/docs/tag-assistant.md but I'm unable to get it running and was posting again here to see if anyone had success with this method or whether the maintainers had implemented something similar to this, as this is the ideal solution for this problem, as it solves the problem of how to connect GTM running in PartyTown to Google Tag Assistant not just running GTM on the main thread

@slawekkolodziej
Copy link
Contributor

@callum-gander, the link you are referring to was my initial work. I ended up wrapping all of that in a slightly more convenient partytown plugin here: https://github.com/superside-oss/partytown-gtm-plugin, did you try using it?

@callum-gander
Copy link

callum-gander commented Feb 9, 2024

Hey @slawekkolodziej, so yes, I haven't gone 100% with your code, but I've broadly used the approach you use within it and used a lot of the code within your repo, which works great, amazing work! Happy to go into detail if people want to know how I did this but I'd strongly recommend anyone having this issue to just use @slawekkolodziej's plugin, the only reason we don't is due to some internal complexities that mean it's better to hand implement

I've broadly got this working except for the issues mentioned below about the TagAssistant banner not loading properly. Any updates on if it's possible to fix this? Or if it causes any further issues? e.g. is it just a minor UI bug and all events will still properly go through?

@sthobis I did not face that specific issue.

By "There are some things that are still not perfect, but it works okay for us" I meant two things: a) TagAssistant banner does not load properly. It shows transparent window with that shadow / border. Exactly what I can see in the screenshot in your post). b) I only implemented API for Tag Assistant browser plugin. If the plugin is missing, my approach won't work.

However there are 3 main parts that needs to be taken care of:

  1. Tag Assistant browser plugin (this adds GTM-specific APIs to the window object)
  2. Code that runs in main thread AND worker to work as a communication channel between GTM and that plugin-specific browser API.
  3. Proxying some GTM-specific JS files as they are missing proper CORS headers

Despite your amazing work reversing all this and getting this working as a separate package, I can't help but feel like this really deserves to be within the main PartyTown repo + docs, not a separate 3P package.

As I raised earlier, GTM is cited as the first use case on the PartyTown docs page here and realistically it's probably the primary reason for adoption for most users, as GTM is so widely used and a complete nightmare on performance. Not having robust handling of debugging GTM with PartyTown (not just turning it off during debugging), both in the library itself and within the documentation as well, is really, really poor DX and feels like a barrier to adoption. Out of interest, why did you set it up as a separate package? Did you raise a PR at all about bringing it into the main repo? Is there any possibility or likelihood of you doing so?

@slawekkolodziej
Copy link
Contributor

Out of interest, why did you set it up as a separate package?

I created bunch of other PRs that made the plugin possible. But I had mixed feelings about creating a separate PR that adds library-specific code to Partytown core. I needed something that I can release & integrate quickly.

But I agree, I would love to have GTM debugging work out of the box when I first tried Partytown.

@callum-gander
Copy link

callum-gander commented Feb 12, 2024

Thanks for your response @slawekkolodziej, that makes sense given the need to just get it working asap. @gioboa you seem to be a frequent contributor, how can we go about getting the ball rolling on integrating this into PartyTown?

Would it be a good idea to add this to the docs as a temporary bandaid, e.g. "use this plugin for debugging GTM for now" and linking @slawekkolodziej's package and then opening a PR to get some of this stuff more natively integrated into the PartyTown library over time? Happy to help with any PRs on this work btw

@gioboa
Copy link
Collaborator

gioboa commented Feb 12, 2024

The best way to integrate that is:

  • to reproduce the problem locally
  • create the code to fix the issue
  • drop a PR to correct the scenario
  • double check the resolution of the scenario

I think we can't create an integration test to check this issue inside the GH actions because we need public keys and different tools

@techfg
Copy link
Contributor

techfg commented Mar 24, 2024

@gioboa - Thanks for merging #573 & #493, great to see that fix made! Regarding this issue, I don't believe it should have been closed. Even with the fix in #573, while the situation with GTM should be improved when not using atomics, there are still issues/limitations with GTM with atomics and service workers that this issue mentions. For example, the workaround provided by @slawekkolodziej is still required and even with that, functionality is not 100% supported when PT is used.

@gioboa gioboa reopened this Mar 25, 2024
@maruthasalamr
Copy link

maruthasalamr commented Apr 3, 2024

I'm getting CORS Policy error even though create reverse proxy for Hubspot analytics

Partytown version 0.10.1
Gatsby version 5.11.0
Web host Provider - AWS Cloudfront
Reverse proxy setup for hubspot analytics in cloudfront

image image image

Reverse Proxy setup uin cloudfront

image

Partytown configuration

Gatsby-ssr file

export const onRenderBody = ({ setHeadComponents, setPreBodyComponents }) => {
  setHeadComponents([
    <Partytown
      key="partytown"
      resolveUrl={(url,location,type) => {       
          if (type === 'script' && url.hostname.includes('analytics')) {
            var proxyUrl = new URL('https://d1gec6izgol1hj.cloudfront.net');
            proxyUrl.searchParams.append('url', url.href);
            return proxyUrl;
          }

          return url;
      }}
      debug={true}
      forward={['dataLayer.push']}
    />,
    <script
      key="plugin-google-tagmanager"
      type="text/partytown"
      dangerouslySetInnerHTML={{
        __html: `(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-KXJZBP');`,
      }}
    />,
  ]),
    setPreBodyComponents([
      <noscript
        key="gtm"
        dangerouslySetInnerHTML={{
          __html: `
                  <iframe src="${ORIGIN}/ns.html?id=${gtmTrackingId}" height="0" width="0"
                      style="display:none;visibility:hidden"></iframe>
                `,
        }}
      />,
    ]);
};

someone can you please help me on this ?

@callum-gander
Copy link

Probably worth mentioning that I'd gotten @slawekkolodziej's solution working but recently, whether it's due to something on our end, an issue with GTM, some change in chrome or an issue with his solution, GTM Assistant now won't connect to GTM in PartyTown. It's not something I'm capable of debugging or something I can post a codesandbox of to demonstrate the issue, I can only point out that going down the root of integrating partytown-gtm is now not working for me. On connecting to GTM Assistant, I get thousands of Tag Assistant Set receiver logs and GTM Assistant says GTM does not exist on the page.

As much as I wanted to keep pursuing this to get it working again, the lack of a concrete solution within the library itself from the core team for what I'd argue is a pretty core usecase and the length of time this issue has been open, kind of makes it difficult for me to justify to my team that it's worth putting more time into it and we won't be using PartyTown any time soon as a result.

I think the @andre-mr's comment sums it up best here #554 (comment). Losing analytics data or issues around being able to guarantee they're working before going to production means that any potential performance gains from PartyTown aren't worth pursuing. In particular the iOS issue at the top of the below issues concerns me

I just thought this might be worth bringing up in case it helps justify additional resources from BuilderIO being put towards issues like this. There's clearly been a lot of amazing work put into this library and it's the only library of it's kind but fixing issues like this one feel core to it's wider adoption. Thanks for all the assistance on this!

@jemys89
Copy link

jemys89 commented Apr 5, 2024

Hello marcowuethrich
I've implemented the same solution you mention in your repository and I'm encountering the same issue mentioned at the end of this thread... Tag Manager's debugging no longer works.

In addition to that, in Angular, navigation fails quite often with Partytown. It's as if the Service Worker is blocking the navigation event... you have to reload the page to navigate properly.

You can validate it here:

If you navigate from the home to the blog, then the cards don't work correctly.
https://find-ida.com/de/blogs

It's a great pity, given the wonderful work that has been done by the community with this library, but I'm afraid I'm going to have to uninstall it due to the high number of issues related to something as important as monitoring users/business.

I'm looking forward to a solution.

Many thanks to everyone!

@indykoning
Copy link
Contributor

indykoning commented May 15, 2024

I'm currently running with tag assistant without issue using
https://github.com/rapidez/gtm/pull/23/files

based on https://github.com/superside-oss/partytown-gtm-plugin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.