Reputation: 29
I'm using nextjs and add google tag manager by script
<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-P35C2ZJ');`,
}}
></script>
but after adding this script in _documetn.js, an unexpected hash appears at the bottom page after the body tag
and here
Upvotes: 0
Views: 250
Reputation: 1628
I think, the @evolutionxbox curiosity is reasonable. There is no reason to use dangerouslySetInnerHTML
.
To add it to your _document.js
, please read the docs first and then follow it.
For example:
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx:any) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render() {
return (
<Html>
<Head>
<script>
{
function ({w, d, s, l, i}: any) {
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-XXXXXX');
</script>
</Head>
<body>
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX" height="0" width="0" style={{ display: 'none', visibility: 'hidden' }}></iframe></noscript>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
_Note: I have tried it in TypeScript. If you are using Javascript, edit it as needed.
Upvotes: 1