3

为 Gatsby 静态站点添加 Adsense 广告

 2 years ago
source link: https://inote.xyz/gatsby-adsense
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
为 Gatsby 静态站点添加 Adsense 广告
为 Gatsby 静态站点添加 Adsense 广告
为 Gatsby 静态站点添加 Adsense 广告
Jan 14, 2020
对于使用 Gatsby 生成的静态站点,并不像 Wordpress 和 Ghost 等建站系统那样,成功插入广告代码并不简单。参考国外两篇博文,把方法总结如下:
  1. 在 Adsense 后台获得固定广告单元代码,不要使用自动代码,现在 Gatsby 还没办法实现自动加载 Adsense 广告。
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><!-- post页广告 --><ins class="adsbygoogle"     style="display:block"     data-ad-client="ca-pub-2527854722096700"     data-ad-slot="7748165687"     data-ad-format="auto"     data-full-width-responsive="true"></ins><script>     (adsbygoogle = window.adsbygoogle || []).push({});</script>
  1. 国内小哥针对 react 网站开发了专门的 React-Adsense 插件。首先,cd 到 Gatsby 站点目录,安装插件。
npm i react-adsense
  1. 复制 .cache目录下的 html.jssrc目录下。
cp .cache / default-html.js src / html.js
  1. 将在 Adsense 后台获得的广告代码,如下两部分添加到 html.js 标签的<head></head> 之间,需要对adsbygoogle进行定义。
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script evilSetInnerHTML = {{__ html:'(window.adsbygoogle = window.adsbygoogle || [])”。 push({});'}}> </ script>
  1. 在需要插入广告的页面如 post 等文件中,插入广告位。
import React from 'react';import AdSense from 'react-adsense'; // ads with no set-up<AdSense.Google  client='ca-pub-7292810486004926'  slot='7806394673'/> // ads with custom format<AdSense.Google  client='ca-pub-7292810486004926'  slot='7806394673'  style={{ width: 500, height: 300, float: 'left' }}  format=''/> // responsive and native ads<AdSense.Google  client='ca-pub-7292810486004926'  slot='7806394673'  style={{ display: 'block' }}  layout='in-article'  format='fluid'/> // auto full width responsive ads<AdSense.Google  client='ca-pub-7292810486004926'  slot='7806394673'  style={{ display: 'block' }}  format='auto'  responsive='true'  layoutKey='-gw-1+2a-9x+5c'/>
  1. 等待广告生效。一般需要1-2天。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK