-
Notifications
You must be signed in to change notification settings - Fork 0
Add Google AdSense script #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
💡 TipWant to run a security-focused check? |
✅ Deploy Preview for xiaomingnn ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary of Changes
Hello @6uu1, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request focuses on integrating Google AdSense into the application's document structure. By adding the necessary script to the document head, the system will be able to load and display advertisements, enabling ad functionality for the website. This change is foundational for monetizing the site through Google's advertising platform.
Highlights
- Google AdSense Integration: The pull request integrates the Google AdSense asynchronous script into the
<Head>component ofpages/_document.js. This script is essential for displaying advertisements on the website.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
File Name: pages/_document.js🔍 Issue Breakdown by Severity and Quality Aspect
|
| <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605" | ||
| crossOrigin="anonymous"></script> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Issue: Directly embedding external script sources without validation may lead to performance or security vulnerabilities.
Quality Aspect: Comprehensive Power Analysis
Severity: Critical
Lines: 46-47
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605"
crossOrigin="anonymous"></script>Solution: Implement a validation or fallback mechanism to handle potential script loading issues.
const script = document.createElement('script');
script.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605";
script.async = true;
script.crossOrigin = "anonymous";
script.onerror = () => console.error('Failed to load adsbygoogle script');
document.head.appendChild(script);
<details>
<summary>审阅者指南 (在小型 PR 上折叠)</summary>
## 审阅者指南
此 PR 通过在文档头部注入异步脚本标签来集成 Google AdSense 脚本,以启用广告功能。
### 文件级别的更改
| 更改 | 详情 | 文件 |
| ------ | ------- | ----- |
| 在文档头部添加 Google AdSense 脚本 | <ul><li>插入了带有客户端 ID 的 Googlesyndication 异步脚本标签</li><li>包含了设置为 anonymous 的 crossOrigin 属性</li></ul> | `pages/_document.js` |
</details>
---
<details>
<summary>提示与命令</summary>
#### 与 Sourcery 交互
- **触发新审阅:** 在拉取请求上评论 `@sourcery-ai review`。
- **继续讨论:** 直接回复 Sourcery 的审阅评论。
- **从审阅评论生成 GitHub issue:** 通过回复审阅评论,让 Sourcery 从中创建一个 issue。你也可以回复审阅评论并带上 `@sourcery-ai issue` 来创建 issue。
- **生成拉取请求标题:** 随时在拉取请求标题的任意位置写入 `@sourcery-ai` 来生成标题。你也可以在拉取请求上评论 `@sourcery-ai title` 来随时(重新)生成标题。
- **生成拉取请求摘要:** 随时在拉取请求正文的任意位置写入 `@sourcery-ai summary`,以便在你希望的位置生成 PR 摘要。你也可以在拉取请求上评论 `@sourcery-ai summary` 来随时(重新)生成摘要。
- **生成审阅者指南:** 随时在拉取请求上评论 `@sourcery-ai guide` 来(重新)生成审阅者指南。
- **解决所有 Sourcery 评论:** 在拉取请求上评论 `@sourcery-ai resolve` 来解决所有 Sourcery 评论。如果你已经解决了所有评论并且不想再看到它们,这会很有用。
- **驳回所有 Sourcery 审阅:** 在拉取请求上评论 `@sourcery-ai dismiss` 来驳回所有现有的 Sourcery 审阅。如果你想从头开始一个新的审阅,这尤其有用——别忘了评论 `@sourcery-ai review` 来触发新的审阅!
#### 自定义你的体验
访问你的 [仪表盘](https://app.sourcery.ai) 以:
- 启用或禁用审阅功能,例如 Sourcery 生成的拉取请求摘要、审阅者指南以及其他功能。
- 更改审阅语言。
- 添加、删除或编辑自定义审阅说明。
- 调整其他审阅设置。
#### 获取帮助
- [联系我们的支持团队](mailto:[email protected]) 以获取问题解答或提供反馈。
- 访问我们的 [文档](https://docs.sourcery.ai) 以获取详细指南和信息。
- 通过在 [X/Twitter](https://x.com/SourceryAI)、[LinkedIn](https://www.linkedin.com/company/sourcery-ai/) 或 [GitHub](https://github.com/sourcery-ai) 上关注我们,与 Sourcery 团队保持联系。
</details>Original review guide in EnglishReviewer's guide (collapsed on small PRs)Reviewer's GuideThis PR integrates the Google AdSense script by injecting an asynchronous script tag into the document head to enable ad functionality. File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
你好 - 我已经审阅了你的修改,它们看起来很棒!
帮助我更有用!请在每条评论上点击 👍 或 👎,我将使用反馈来改进你的审阅。
Original comment in English
Hey there - I've reviewed your changes and they look great!
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
WalkthroughAdds an async Google AdSense script tag to the Head in pages/_document.js. No other logic or exports are modified. Changes
Estimated code review effort🎯 1 (Trivial) | ⏱️ ~2 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review by Korbit AI
Korbit automatically attempts to detect when you fix issues in new commits.
| Category | Issue | Status |
|---|---|---|
| Hardcoded AdSense Client ID ▹ view |
Files scanned
| File Path | Reviewed |
|---|---|
| pages/_document.js | ✅ |
Explore our documentation to understand the languages and file types we support and the files we ignore.
Check out our docs on how you can make Korbit work best for you and your team.
| <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605" | ||
| crossOrigin="anonymous"></script> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hardcoded AdSense Client ID 
Tell me more
What is the issue?
The Google AdSense script is using a hardcoded client ID directly in the document, which could lead to issues if different environments (development, staging, production) require different AdSense accounts.
Why this matters
Using a hardcoded client ID makes it difficult to manage different AdSense accounts across environments and could result in incorrect ad tracking or revenue attribution.
Suggested change ∙ Feature Preview
Move the AdSense client ID to an environment variable or configuration file. Example:
<script
async
src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_ADSENSE_ID}`}
crossOrigin="anonymous"
/>Provide feedback to improve future suggestions
💬 Looking for more details? Reply to this comment to chat with Korbit.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request adds the Google AdSense script to the document head. My review identifies a critical issue where the AdSense client ID is hardcoded instead of using the existing configuration from blog.config.js. This makes maintenance difficult and goes against the project's established configuration pattern. Additionally, I've pointed out that this change introduces redundant script loading, as similar logic already exists in components/GoogleAdsense.js, which could lead to performance problems. I've provided a code suggestion to fix the hardcoded ID and recommended consolidating the script loading logic.
| <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605" | ||
| crossOrigin="anonymous"></script> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There are a couple of issues with this change:
-
Hardcoded Client ID: The AdSense client ID is hardcoded. The project already has a configuration for this in
conf/ad.config.jsasADSENSE_GOOGLE_ID. You should use the value from the configuration (BLOG.ADSENSE_GOOGLE_ID) to avoid hardcoding and make it easily manageable. It's also best practice to only render this script if an ID is provided. -
Redundant Script Loading: The file
components/GoogleAdsense.jscontains a functioninitGoogleAdsensethat also programmatically loads this script. Loading the script twice is unnecessary and can lead to performance issues or unexpected ad behavior.
Please refactor this to use the configured AdSense ID and ensure the script is loaded only once. Loading it here in _document.js is a good approach, which would mean the loading logic in initGoogleAdsense should be removed.
{BLOG.ADSENSE_GOOGLE_ID && <script async src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${BLOG.ADSENSE_GOOGLE_ID}`} crossOrigin="anonymous"></script>}There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
cubic analysis
1 issue found across 1 file • Review in cubic
React with 👍 or 👎 to teach cubic. You can also tag @cubic-dev-ai to give feedback, ask questions, or re-run the review.
| return ( | ||
| <Html lang={BLOG.LANG}> | ||
| <Head> | ||
| <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using a raw <script> tag inside _document.js violates Next.js best-practices and the @next/next/no-document-script-tags ESLint rule. Prefer the <Script> component from next/script, or relocate the tag to a regular page/component so that the script can be loaded and optimised correctly.
Prompt for AI agents
Address the following comment on pages/_document.js at line 46:
<comment>Using a raw <script> tag inside _document.js violates Next.js best-practices and the @next/next/no-document-script-tags ESLint rule. Prefer the <Script> component from `next/script`, or relocate the tag to a regular page/component so that the script can be loaded and optimised correctly.</comment>
<file context>
@@ -43,6 +43,8 @@ class MyDocument extends Document {
return (
<Html lang={BLOG.LANG}>
<Head>
+ <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605"
+ crossOrigin="anonymous"></script>
{/* 预加载字体 */}
</file context>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (1)
pages/_document.js (1)
46-47: Use Next.js Script with a non-blocking strategy and error handlingLoad the AdSense script via
next/scriptto benefit from Next.js loading optimizations and add a failure handler. This also addresses the prior feedback about handling script load errors.Apply this diff within the selected lines:
- <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605" - crossOrigin="anonymous"></script> + <Script + id="adsense" + strategy="afterInteractive" + src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605" + crossOrigin="anonymous" + onError={(e) => { console.error('Failed to load adsbygoogle script', e) }} + />Additionally, add this import at the top of the file (outside the selected range):
import Script from 'next/script'
🧹 Nitpick comments (2)
pages/_document.js (2)
46-47: Gate loading with env/config to avoid hard-coding publisher ID and to disable in non-prodAvoid committing a hard-coded
ca-pubID and ensure this only loads in environments where ads should run.Apply this diff within the selected lines:
- <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605" - crossOrigin="anonymous"></script> + {process.env.NEXT_PUBLIC_GOOGLE_ADSENSE_ID && ( + <Script + id="adsense" + strategy="afterInteractive" + src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_GOOGLE_ADSENSE_ID}`} + crossOrigin="anonymous" + onError={(e) => { console.error('Failed to load adsbygoogle script', e) }} + /> + )}Note: ensure
NEXT_PUBLIC_GOOGLE_ADSENSE_ID=ca-pub-xxxxxxxxxxxxxxxxis set in your environment.
46-47: Optional: Preconnect to AdSense domains for faster script fetchPreconnect can shave time off the first ad request.
For example, add before the script:
+ <link rel="preconnect" href="https://pagead2.googlesyndication.com" crossOrigin="anonymous" /> + <link rel="preconnect" href="https://googleads.g.doubleclick.net" crossOrigin="anonymous" />
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
pages/_document.js(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
pages/_document.js (1)
components/ExternalScript.js (1)
script(20-20)
| <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605" | ||
| crossOrigin="anonymous"></script> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Verify CSP, consent, and duplication before merging
- If you use a Content Security Policy, allow the required AdSense domains (
pagead2.googlesyndication.com,googleads.g.doubleclick.net, etc.). - Ensure a user consent mechanism (GDPR/CCPA) is in place if required for your audience.
- Confirm this script isn’t injected elsewhere to avoid duplicate loads.
Run this script to check for duplicates and basic signals for CSP/consent:
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Searching for other AdSense script tags..."
rg -n "adsbygoogle\.js" -A2 -B2 || true
echo
echo "Checking for AdSense ID gating via env/config..."
rg -n "NEXT_PUBLIC_GOOGLE_ADSENSE_ID|ADSENSE_GOOGLE_ID|ca-pub-" || true
echo
echo "Looking for CSP headers/meta..."
rg -n "Content-Security-Policy|csp" -A2 -B2 || true
fd -t f "next.config.*" | while read -r f; do echo "---- $f ----"; sed -n '1,200p' "$f"; echo; done
echo
echo "Scanning for consent/cookie handling (GDPR/CCPA)..."
rg -n "consent|cookie|gdpr|ccpa" || trueLength of output: 76411
Action required — centralize/gate AdSense, add CSP allowlist and a consent gate, and remove duplicate loads
Quick summary: repo contains an unconditional AdSense script in pages/_document.js plus other AdSense loaders; no CSP entries found and no clear consent/CMP. This can cause duplicate loads and compliance/CSP issues.
Files that need attention
- pages/_document.js (lines ~46–47) — unconditional: <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7901026683522605" crossOrigin="anonymous"></script> — remove or make conditional (currently bypasses existing env/config).
- components/GoogleAdsense.js (≈lines 63–68, 115, 129, 143, 156, 166, 180+) — already contains dynamic loader using ADSENSE_GOOGLE_ID; prefer this centralized approach and keep only one loader.
- conf/ad.config.js (line ~6) — ADSENSE_GOOGLE_ID is read from NEXT_PUBLIC_ADSENSE_GOOGLE_ID; use this instead of hard-coded ca-pub in _document.js.
- components/ExternalPlugins.js (≈166–168), themes/next/components/SideAreaRight.js (line 38, contains data-ad-client='ca-pub-2708419466378217'), themes/fukasawa/components/BlogListPage.js (line 79) — reconcile publisher IDs and ensure these do not cause duplicate script injection.
- next.config.js — headers function currently does not set a Content-Security-Policy. If you enforce CSP, add script-src/connect-src entries to allow pagead2.googlesyndication.com, googleads.g.doubleclick.net, googletagservices.com, etc.
- Consent/CMP — repo search found cookie libs but no explicit consent flow (GDPR/CCPA). Ensure ads are only initialized after required user consent.
Recommended minimal changes
-
Remove the hard-coded script from pages/_document.js or replace it with a conditional load using your configured ADSENSE_GOOGLE_ID and consent check, e.g.:
{siteConfig('ADSENSE_GOOGLE_ID') && userHasGivenAdConsent && (
<script async src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${siteConfig('ADSENSE_GOOGLE_ID')}`} crossOrigin="anonymous"></script>)}
-
Or, remove the static tag and rely on components/GoogleAdsense.js + ExternalPlugins.js to load the script once (they already gate on ADSENSE_GOOGLE_ID).
-
Update next.config.js headers (or server responses/meta) to include a CSP allowing AdSense domains if you enforce CSP.
-
Add/verify a consent mechanism (or ensure you only initialize initGoogleAdsense after consent) and confirm that the same ca-pub ID is used consistently where intended.
Reason: the repo currently has multiple injection points and a hard-coded client ID which can cause duplicate loads and inconsistent publisher IDs; there’s no CSP allowlist nor an explicit consent gate detected.
🤖 Prompt for AI Agents
pages/_document.js lines ~46–47: there is an unconditional AdSense script tag
hard-coded with ca-pub-7901026683522605 which causes duplicate loads and
bypasses config/consent; remove this static tag or replace it with a conditional
render that checks the centralized ADSENSE_GOOGLE_ID
(NEXT_PUBLIC_ADSENSE_GOOGLE_ID / conf/ad.config.js) and a user consent flag, and
instead rely on the existing components/GoogleAdsense.js (and
ExternalPlugins.js) as the single loader; reconcile all other occurrences of
data-ad-client/IDs (ExternalPlugins.js, themes/* files) to use the same
configured ID or remove duplicates; add corresponding script-src/connect-src
entries for AdSense domains to next.config.js headers CSP if you enforce CSP;
finally ensure ads initialization only runs after explicit user consent (gate
initGoogleAdsense behind consent).
Integrate the Google AdSense script into the document head for ad functionality.
Sourcery 总结
新功能:
Original summary in English
Summary by Sourcery
New Features:
Summary by CodeRabbit
Description by Korbit AI
What change is being made?
Add Google AdSense script to the
_document.jsfile to enable advertisement capabilities on the site.Why are these changes being made?
This change allows the website to display Google advertisements, providing an avenue for monetization. Inserting the script asynchronously ensures it does not block the rendering of the page, aligning with best practices for improving page load performance.