google AdSense
官方文档
链接: AdSense 代码简介
链接: Ad Placement API
链接: H5 游戏广告(Beta 版)使用入门
接入步骤
- 在bulid-templete下创建打包模板。并在index.html文件的 body 中加载sdk并完成初始化
//sdk加载,上线前将src得client换为自己的正式id。并删除data-adbreak-test="on"。
<script async
data-adbreak-test="on"
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-123456789"
crossorigin="anonymous">
</script>
//sdk初始化。需在onReady中传消息/置一个状态给cocos。告知可以开始广告调用。或提示广告加载失败/加载中。
<script>
window.adsbygoogle = window.adsbygoogle || [];
window.adBreak = function (o) { adsbygoogle.push(o); }
window.adConfig = function (o) { adsbygoogle.push(o); }
window.adConfig({
sound: 'on',
preloadAdBreaks: 'on',
onReady: () => {
console.log("AdSense onReady");
},
})
- 在游戏的广告位置调用代码
- 激励
showRewardAd() {
window["adBreak"] && window["adBreak"]({
type: 'reward', // ad shows at start of next level
name: 'restart-game',
beforeAd: () => {
console.log("激励视频开始播放");
}, // You may also want to mute the game's sound.
afterAd: () => {
console.log("激励视频播放结束");//关闭,观看完成都会走这里
}, // resume the game flow.
beforeReward: (showAdFn) => {
showAdFn && showAdFn();
},
adDismissed: () =>{
console.log("中途关闭广告");
},
adViewed: () => {
console.log("玩家完整看完广告");//google建议设置状态码,在afterAd中处理奖励逻辑
},
adBreakDone: () => {
//Always called (if provided) even if an ad didn't show(始终调用,即使广告展示失败了)
}
});
}
- 前贴片广告(理解类似于原生的开屏广告),可以直接在广告加载的onReady中调用
// Game must not be running.
// Nothing in the game area should be clickable
showTailAd() {
window["adBreak"]({
type: 'preroll',
adBreakDone: (e) => {
console.log("前贴片显示失败:", e);
},
})
}
- 插屏
showInterstitialAd() {
window["adBreak"] && window["adBreak"]({
type: 'browse',
name: 'restart-game',
beforeAd: () => {
console.log("插屏");
}, // You may also want to mute the game's sound.
afterAd: () => {
console.log("插屏");
}, // resume the game flow.
});
}
- 随后打包web,在本地使用node起一个http服务器即可测试该代码