Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在nextJS typescript中添加GTM(window.dataLayer不是函数)_Typescript_Next.js_Google Tag Manager_Google Datalayer - Fatal编程技术网

如何在nextJS typescript中添加GTM(window.dataLayer不是函数)

如何在nextJS typescript中添加GTM(window.dataLayer不是函数),typescript,next.js,google-tag-manager,google-datalayer,Typescript,Next.js,Google Tag Manager,Google Datalayer,我正在我的网站上实现GTM,但我的NextJS项目是用Typescript实现的。 我使用了Github的示例,但出现以下错误: TypeError:window.dataLayer不是函数 这是我的gtm.js文件: export const GTM_ID = process.env.TAG_MANAGER export const pageview = (url) => { window.dataLayer({ event: 'pageview', page:

我正在我的网站上实现GTM,但我的NextJS项目是用Typescript实现的。 我使用了Github的示例,但出现以下错误: TypeError:window.dataLayer不是函数

这是我的gtm.js文件:

export const GTM_ID = process.env.TAG_MANAGER

export const pageview = (url) => {
  window.dataLayer({
    event: 'pageview',
    page: url,
  })
}
是的,GTM是js格式的,但是我所有的项目都是ts/tsx格式的

My_app.tsx和My_document.tsx与vercel的示例相同,我创建了具有ID的组件和.env

一切都与本应起作用的示例相同

编辑 我改变了一些事情

My\u document.tsx:

import Document, { DocumentContext, DocumentInitialProps, Head, Html, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
import favicon from '../assets/favicon.ico'
import { GA_TRACKING_ID } from '../lib/gtag'
import { GTM_ID } from '../lib/gtm'

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> { //oda func async recebe promise
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal()
    }
  }

  render(): JSX.Element {
    //change HTML lang
    return(
      <Html lang={"pt"}>
        <Head>
          <meta charSet="utf-8" />
          <link rel="preconnect" href="https://fonts.gstatic.com"></link>
          <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet"></link>
          <link rel="icon" href={favicon} />
          <meta name="theme-color" content="#448757" />
          <link rel="apple-touch-icon" href={favicon}></link>

          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
            }}
          />

          {/* Google Tag Manager - Global base code */}
          <script
            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>
          <noscript>
            <iframe
              src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`}
              height="0"
              width="0"
              style={{ display: 'none', visibility: 'hidden' }}
            />
          </noscript>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
import { AppProps } from 'next/app'
import GlobalStyles  from '../styles/GlobalStyles'
import dynamic from 'next/dynamic'
import { traducao } from '../translate/index'
import { useRouter, Router } from "next/router"
import * as gtag from '../lib/gtag'
import { GTMPageView } from '../lib/gtm'
import React, { useEffect } from 'react';

const MyApp: React.FC<AppProps> = ({ Component, pageProps }) => {
  //Gtag
  const router = useRouter()
    useEffect(() => {
      const handleRouteChange = (url) => {
        gtag.pageview(url)
      }

      router.events.on('routeChangeComplete', handleRouteChange)
        return () => {
          router.events.off('routeChangeComplete', handleRouteChange)
      }
    }, [router.events])


    // Initiate GTM
    useEffect(() => {
      const handleRouteChange = (url: string) => GTMPageView(url);
      Router.events.on('routeChangeComplete', handleRouteChange);
      return () => {
          Router.events.off('routeChangeComplete', handleRouteChange);
      };
    }, []);
  return (
    <>
      <Component {...pageProps}/>
      <GlobalStyles />
    </>
  )
}

export default MyApp
export const GTM_ID = process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID


export const GTMPageView = (url: string) => {
  interface PageEventProps {
      event: string;
      page: string;
  }

  const pageEvent: PageEventProps = {
      event: 'pageview',
      page: url,
  };
  //@ts-ignore
  window && window.dataLayer && window.dataLayer.push(pageEvent);
  return pageEvent;
};
运作良好 但我不知道它是否在GTM中工作,因为我的站点仍在开发中(localhost)

window.datalayer脚本错误消失了,但要知道这是我的灯塔:


最佳实践Google lighthouse error

使用React Google Tag Manager软件包,您可以简化您的生活

用法非常简单:

在_app.js的函数组件定义中

React.useEffect(() => {

    if (typeof window !== 'undefined') {
      console.log("init GTM")
      TagManager.initialize({ gtmId: 'YOUR_GTM_ID' });
    }else {
      console.log("GTM server side - ignorning")
    }

}, [])

您可以使用React Google Tag Manager软件包简化您的生活

用法非常简单:

在_app.js的函数组件定义中

React.useEffect(() => {

    if (typeof window !== 'undefined') {
      console.log("init GTM")
      TagManager.initialize({ gtmId: 'YOUR_GTM_ID' });
    }else {
      console.log("GTM server side - ignorning")
    }

}, [])

您能在
\u document.tsx
中显示您的实际代码吗?当您检查HTML时,GTM脚本是否加载到
元素中。。。我刚刚找到了一个解决方案,看起来很有效,但现在在我的lighthouse中出现了这样的情况:浏览器错误被记录到控制台上,但我将添加更改通过打开Google Tag Manager容器来解决404错误。我只需要发布该站点?由于im仍在本地主机中,您能否在
\u document.tsx
中显示您的实际代码?当您检查HTML时,GTM脚本是否加载到
元素中。。。我刚刚找到了一个解决方案,看起来很有效,但现在在我的lighthouse中出现了这样的情况:浏览器错误被记录到控制台上,但我将添加更改通过打开Google Tag Manager容器来解决404错误。我只需要发布该站点?因为我仍然在本地主机中,所以作者不建议这样做。检查这个;作者不建议这样做。检查这个;