You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用dangerouslySetInnerHTML时Adsense广告无法显示

解决dangerouslySetInnerHTML中Adsense广告不显示的问题

核心原因

React的dangerouslySetInnerHTML不会执行插入的<script>标签,你嵌入的Adsense脚本无法被加载和执行,这是广告不显示的根本原因。

具体解决步骤

1. 全局提前加载Adsense主脚本

不要把Adsense的主脚本放在动态HTML片段里,直接在React应用的public/index.html的<head>中添加:

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7107200228987000" crossorigin="anonymous"></script>

或者在应用入口文件(如index.js)中通过动态创建脚本的方式加载,确保脚本全局可用。

2. 简化动态HTML片段

移除Chapter1.html片段里的重复脚本,只保留广告容器标签:

<p>The hour’s just 9 o’clock.</p>
<p>I should do laundry, clean and spend my time in the morning relaxing.</p>
<p></p>
<ins class="adsbygoogle" style="display:block; text-align:center;" data-ad-layout="in-article"
     data-ad-format="fluid" data-ad-client="ca-pub-7107200228987000" data-ad-slot="9551463795"></ins>
<h3>Part 1</h3>
<p>Inside Keyaki Mall in the forenoon, the atmosphere of Christmas Eve was in full swing.</p>
<p>Inside the mall was decorated with even more gaudy ornaments than at the entrance.</p>

3. 组件内手动触发广告初始化

在渲染动态内容的React组件中,用useEffect监听内容变化,手动调用Adsense初始化方法:

import { useEffect, useRef } from 'react';

function ArticleViewer({ dynamicHtml }) {
  const contentRef = useRef(null);

  useEffect(() => {
    if (!window.adsbygoogle) return;
    
    // 找到所有广告容器并初始化
    const adElements = contentRef.current?.querySelectorAll('.adsbygoogle');
    adElements?.forEach(() => window.adsbygoogle.push({}));
  }, [dynamicHtml]);

  return (
    <div ref={contentRef} dangerouslySetInnerHTML={{ __html: dynamicHtml }} />
  );
}

4. 额外排查点

  • 确认Adsense账号已通过审核,广告单元配置无误
  • 测试时关闭广告屏蔽插件
  • 避免在同一页面重复加载adsbygoogle脚本

内容的提问来源于stack exchange,提问作者Mihir Savla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:05:13