Google AdSense 集成
Google AdSense 用于在网站展示广告并获得收益。AdSense 的接入一般分成两部分:
- 平台侧:申请 AdSense、添加站点、通过审核、创建广告单元
- 代码侧:插入 AdSense 脚本、(可选)插入广告位组件、验证是否出广告
前置条件
- 站点已部署到生产环境
- 站点有基础内容与必要页面(例如 About/Privacy/Terms 等),提升审核通过率
第一步:申请与添加站点
- 进入 AdSense:
https://www.google.com/adsense/ - 按流程注册/登录,提交站点 URL
- 按指引完成站点所有权验证
将代码提示里 ca-pub- 后面的字符复制出来,粘贴到环境变量 NEXT_PUBLIC_GOOGLE_ADSENSE_ID
.env
NEXT_PUBLIC_GOOGLE_ADSENSE_ID=xxxxxxxxxxxx再将 txt 验证的内容粘贴到 public/ads.txt
第四步:选择“自动广告”或“广告单元”
方式 A:自动广告
在 AdSense 后台开启 Auto ads 后,Google 会自动选择位置展示广告。
此方式只要按照上面的步骤操作即可生效。
方式 B:手动广告位
如果你想在某些固定位置展示广告,需要创建广告单元并在页面中插入广告位。
一个常见的实现方式是在前端做一个 AdSlot 组件:
"use client";
import { useEffect } from "react";
type AdSlotProps = {
adSlot: string;
adFormat?: string;
fullWidthResponsive?: boolean;
};
export function AdSlot({
adSlot,
adFormat = "auto",
fullWidthResponsive = true,
}: AdSlotProps) {
const client = process.env.NEXT_PUBLIC_GOOGLE_ADSENSE_ID;
useEffect(() => {
try {
// @ts-expect-error adsbygoogle is injected by AdSense
(window.adsbygoogle = window.adsbygoogle || []).push({});
} catch {
// ignore
}
}, []);
if (!client) return null;
return (
<ins
className="adsbygoogle"
style={{ display: "block" }}
data-ad-client={client}
data-ad-slot={adSlot}
data-ad-format={adFormat}
data-full-width-responsive={fullWidthResponsive ? "true" : "false"}
/>
);
}把 AdSense 后台生成的 data-ad-slot 填到 adSlot,然后在你想展示的位置渲染 <AdSlot />。