我正在尝试将Google Adsense集成到我的React网站中并遇到问题。为了在我的网页上展示广告,我已将以下脚本标签包含在html文件的head中:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

广告包装在一个简单的组件中,如下所示:
export default class GoogleAdSense extends Component {
  componentDidMount() {
    (window.adsbygoogle = window.adsbygoogle || []).push({});
  }

  render() {
    const {
      showAd,
      className,
      slot,
      format,
    } = this.props;

    return (
      <div className="GoogleAdSense">
        <ins
          className={ `adsbygoogle ${className}` }
          style={{ display: 'block' }}
          data-ad-client="ca-pub-7104738102834759"
          data-ad-slot={slot}
          data-ad-format={format}
        >
        </ins>
      </div>
    );
  }
}

由其他组件呈现,如下所示:
<GoogleAdSense
  slot="3461840703"
  className="QuestionGoogleAd"
  format="auto"
/>

此方法是从this文章中提取的

使用上述实现方式,广告可以正确地加载到页面上。用户导航到其他页面时会出现问题。由于我使用的是React Router,因此磁头不会更新(某些React-Helmet标题更改除外),并且Adsense脚本不会重新加载。这使Adsense认为它与我所获得的Adsense浏览量数字和Adsense docs here所指示的页面位于同一页面上:



事实进一步证明了这一点,当我检查Adsense HTTP请求时,可以看到有一个prev_fmts参数可以记住先前请求的广告:

javascript - 在React &#43; React Router上使用Google Adsense-LMLPHP

问题是,在大约显示12-16个广告(每页2个,因此最多8次页面浏览)后,Adsense会为每个后续广告请求返回一个空HTML文档,并显示400错误:

javascript - 在React &#43; React Router上使用Google Adsense-LMLPHP
javascript - 在React &#43; React Router上使用Google Adsense-LMLPHP

如果我通过点击cmd-r手动刷新页面,则广告会再次正确加载,但仅适用于接下来的几次浏览。我尝试删除了前面提到的script,并将其重新插入每个页面更改的头部,因为从理论上讲,这将重新运行广告代码并触发新的Adsense浏览量,但这没有用。这个网站的重点是能够展示广告以产生稳定的收入来源,如果我不能使用React在所有的浏览量中展示广告(我目前平均每个用户约20个),将不得不重新实现整个网站,而我确实是不想做的。其他人有没有遇到过这种情况并找到了解决方案?

最佳答案

您可以改用googletags管理您的adsense显示。

https://www.google.com/analytics/tag-manager/

它们具有刷新页面https://support.google.com/dfp_sb/answer/2694377?visit_id=1-636301421618198678-920866889&rd=1上的广告的功能,该功能适用​​于客户端应用

关于javascript - 在React + React Router上使用Google Adsense,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43922455/

10-11 23:26