avatar
08.【个人网站】接入Google广告营收插件
✔️

08.【个人网站】接入Google广告营收插件

published_date
最新编辑 2024年09月08日
slug
接入Google广告营收插件
tags
Website
在 Next.js 项目中集成 Google AdSense 广告,可以按照以下步骤进行:

集成相关代码

1. 添加 AdSense 验证代码到 <Head>

首先,你需要在 Next.js 项目的 _document.js 文件中添加 AdSense 验证代码到 <Head> 部分。
创建或修改 pages/_document.js 文件:
import Document, { Html, Head, Main, NextScript } from 'next/document'; class MyDocument extends Document { render() { return ( <Html> <Head> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" /> <script dangerouslySetInnerHTML={{ __html: ` (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-XXXXXXXXXXXXXXXX", // 替换为你的广告客户端ID enable_page_level_ads: true }); `, }} /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } export default MyDocument;

2.在页面或组件中添加广告单元

你可以在任何页面或组件中插入 AdSense 广告单元。以下是一个示例,展示如何在一个组件中插入广告:
创建一个新的广告组件 components/AdSense.js
import { useEffect } from 'react'; const AdSense = () => { useEffect(() => { try { (window.adsbygoogle = window.adsbygoogle || []).push({}); } catch (err) { console.error('Adsense error:', err); } }, []); return ( <ins className="adsbygoogle" style={{ display: 'block' }} data-ad-client="ca-pub-XXXXXXXXXXXXXXXX" // 替换为你的广告客户端ID data-ad-slot="XXXXXXXXXX" // 替换为你的广告位ID data-ad-format="auto" data-full-width-responsive="true" ></ins> ); }; export default AdSense;
在页面或其他组件中使用 AdSense 组件:
import AdSense from '../components/AdSense'; const HomePage = () => { return ( <div> <h1>欢迎来到我的网站</h1> <p>这里是一些内容。</p> <AdSense /> <p>这里是更多内容。</p> </div> ); }; export default HomePage;

注意事项

  1. 广告展示延迟:Google AdSense 广告可能需要一些时间才能开始展示广告,尤其是当首次配置广告时。确保 AdSense 账户已通过验证,并且广告位已被批准。
    1. notion image
  1. 广告位配置:确保在 Google AdSense 管理控制台中正确配置了广告位。
notion image
  1. 开发环境中禁用广告:为了避免开发环境中展示广告,可以在生产环境中仅加载广告代码。例如:
    1. const AdSense = () => { useEffect(() => { if (process.env.NODE_ENV === 'production') { try { (window.adsbygoogle = window.adsbygoogle || []).push({}); } catch (err) { console.error('Adsense error:', err); } } }, []); return ( <ins className="adsbygoogle" style={{ display: 'block' }} data-ad-client="ca-pub-XXXXXXXXXXXXXXXX" // 替换为你的广告客户端ID data-ad-slot="XXXXXXXXXX" // 替换为你的广告位ID data-ad-format="auto" data-full-width-responsive="true" ></ins> ); };

About

My desire to practice my skills and share my acquired knowledge fuels my endeavors.

Contact Me : znjessie858@gmail.com

Subscribe

Subscribe to receive notifications of my latest posts and unsubscribe at any time!