forked from tangly1024/NotionNext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGoogleAdsense.js
97 lines (87 loc) · 3.09 KB
/
GoogleAdsense.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import BLOG from '@/blog.config'
import { loadExternalResource } from '@/lib/utils'
import { useRouter } from 'next/router'
import { useEffect } from 'react'
/**
* 初始化谷歌广告
* @returns
*/
export default function GoogleAdsense() {
const initGoogleAdsense = () => {
// GoogleAdsense 本地开发请加入 data-adbreak-test="on"
// {BLOG.ADSENSE_GOOGLE_ID && <script async src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${BLOG.ADSENSE_GOOGLE_ID}`}
// crossOrigin="anonymous" />}
loadExternalResource(`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${BLOG.ADSENSE_GOOGLE_ID}`, 'js').then(url => {
setTimeout(() => {
const ads = document.getElementsByClassName('adsbygoogle')
const adsbygoogle = window.adsbygoogle
if (ads.length > 0) {
for (let i = 0; i <= ads.length; i++) {
try {
adsbygoogle.push(ads[i])
console.log('adsbygoogle', i, ads[i], adsbygoogle)
} catch (e) {
}
}
}
}, 100)
})
}
const router = useRouter()
useEffect(() => {
// 延迟3秒加载
setTimeout(() => {
initGoogleAdsense()
}, 3000)
}, [router])
return null
}
/**
* 文章内嵌广告单元
* 请在GoogleAdsense后台配置创建对应广告,并且获取相应代码
* 修改下面广告单元中的 data-ad-slot data-ad-format data-ad-layout-key(如果有)
* 添加 可以在本地调试
*/
const AdSlot = ({ type = 'show' }) => {
if (!BLOG.ADSENSE_GOOGLE_ID) {
return null
}
// 文章内嵌广告
if (type === 'in-article') {
return <ins className="adsbygoogle"
style={{ display: 'block', textAlign: 'center' }}
data-ad-layout="in-article"
data-ad-format="fluid"
data-adtest={BLOG.ADSENSE_GOOGLE_TEST ? 'on' : 'off'}
data-ad-client={BLOG.ADSENSE_GOOGLE_ID}
data-ad-slot={BLOG.ADSENSE_GOOGLE_SLOT_IN_ARTICLE}></ins>
}
// 信息流广告
if (type === 'flow') {
return <ins className="adsbygoogle"
data-ad-format="fluid"
data-ad-layout-key="-5j+cz+30-f7+bf"
style={{ display: 'block' }}
data-adtest={BLOG.ADSENSE_GOOGLE_TEST ? 'on' : 'off'}
data-ad-client={BLOG.ADSENSE_GOOGLE_ID}
data-ad-slot={BLOG.ADSENSE_GOOGLE_SLOT_FLOW}></ins>
}
// 原生广告
if (type === 'native') {
return <ins className="adsbygoogle"
style={{ display: 'block', textAlign: 'center' }}
data-ad-format="autorelaxed"
data-adtest={BLOG.ADSENSE_GOOGLE_TEST ? 'on' : 'off'}
data-ad-client={BLOG.ADSENSE_GOOGLE_ID}
data-ad-slot={BLOG.ADSENSE_GOOGLE_SLOT_NATIVE}></ins>
}
// 展示广告
return <ins className="adsbygoogle"
style={{ display: 'block' }}
data-ad-client={BLOG.ADSENSE_GOOGLE_ID}
data-adtest={BLOG.ADSENSE_GOOGLE_TEST ? 'on' : 'off'}
data-ad-slot={BLOG.ADSENSE_GOOGLE_SLOT_AUTO}
data-ad-format="auto"
data-full-width-responsive="true"></ins>
}
export { AdSlot }