使用cocoscreator接入google AdSence广告

这篇博客详细介绍了如何在H5游戏中集成Google AdSense,包括激励视频、前贴片广告和插屏广告的实现步骤。从加载SDK到初始化,再到不同类型的广告调用方法,提供了完整的代码示例,帮助开发者实现游戏内的广告展示功能。
摘要由CSDN通过智能技术生成

google AdSense

官方文档

链接: AdSense 代码简介
链接: Ad Placement API
链接: H5 游戏广告(Beta 版)使用入门

接入步骤

  1. 在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");
  },
})
  1. 在游戏的广告位置调用代码
  • 激励
  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.
        });
    }
  1. 随后打包web,在本地使用node起一个http服务器即可测试该代码
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小蟹 !

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值