next.js 添加 adsense代码

实战 nextjs 接入谷歌adsense广告


第一步

创建components/ad.js 需要引用 yarn add uuid

import { useEffect } from 'react'

const Ad = ({ children }) => {
    useEffect(() => {
        try {
            (window.adsbygoogle = window.adsbygoogle || []).push({});
        } catch (error) {
            console.log(error);
        }
    }, [])

    return (
        <>{children}</>
    )
}

export default Ad

第二步

创建 pages/_document.js

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
    static async getInitialProps(ctx) {
        const initialProps = await Document.getInitialProps(ctx)
        return { ...initialProps }
    }

    render() {
        return (
            <Html>
                <Head>
                    {/* Adsense */}
                    <script key="adsense" data-ad-client="ca-pub-xxx" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>                 
                </Head>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        )
    }
}

export default MyDocument

第三步

在需要广告的位置引用ad组件,并且为每个ad组件生成唯一的key,在route改变时才会重新加载广告。

import Ad from 'components/ad'
import { v4 as uuidv4 } from 'uuid';

export default function somePage(){
return (
...
            <Ad `key={uuidv4()}`>
                <ins className="adsbygoogle"
                    style={{ display: 'block' }}
                    data-ad-client="ca-pub-xxx"
                    data-ad-slot="xxx"
                    data-ad-format="auto"
                    data-full-width-responsive="true"></ins>
            </Ad>
...
)}

完事


注意:

不要把代码放入layout或者其他地方,一定要放在_document.js的 head中。

否则你可能会遇到这个错误`

`"adsbygoogle.push() error: Only one AdSense head tag supported per page. The second tag is ignored."`

还可以参考: https://github.com/vercel/next.js/issues/4838


vercel,nextjs 交流群:815526049