问题描述:

H5快游戏当前没有开放广告API接口,如何实现接入广告服务

问题分析:

当前广告服务只支持快应用和runtime快游戏,H5快游戏暂时不支持直接接入广告接口,当前提供临时方案解决此问题,可以通过快游戏ux页面中的web组件和游戏H5网页之间的双向通信机制实现。在ux页面的onMessage生命周期函数接收H5页面的消息,然后接入快应用的广告API接口获取广告信息(仅支持原生广告和激励视频广告),最后将获取的广告信息通过this.$element(‘web’).postMessage({ message: JSON.stringify(result) });发送给H5页面。

解决方法:

建议将广告创建和请求的过程单独写函数封装,不要放在onInit或者onMessage生命周期函数里面,这是由于onInit函数是在页面初始化时调用,加载速度快,不适合处理复杂逻辑;onMessage函数只负责接收H5网页传递的字符串消息,加判断分支后调用对应的函数走相应的广告处理流程即可。

注意:当前快应用框架只支持在onInit函数中创建广告对象,暂不支持在onMessage等函数中创建,请保持该块代码位置不变。

快应用ux示例代码:

<template><div class="doc-page"><web class="web-page" src="{{webUrl}}" type="game" trustedurl="{{list}}" onpagestart="onPageStart"useragent="default"onmessage="onMessage"fullscreendirection="{{fullscreenDirection}}" jumppolicy="{{linkJumpPolicy}}" multiwindow="{{openMultiwindow}}"onpagefinish="onPageFinish" ontitlereceive="onTitleReceive" onerror="onError"id="web"allowthirdpartycookies="{{allowThirdPartyCookies}}"></web></div>
</template><style>.doc-page {flex-direction: column;flex-direction: column;justify-content: center;align-content: center;align-items: center;}.web-page {width: 100%;height: 100%;}
</style>
<script>import router from "@system.router"import prompt from '@system.prompt'import ad from "@service.ad"let nativeAdlet rewardedVideoAdexport default {props: ['websrc'],data: {native: {adUnitId: 'testu7m3hc4gvm',adData: {},errStr: '', },rewarded: {adUnitId: 'testx9dtjwj8hp',isShow: 'false',errStr: ''},title: "",// TODO Replace the link to the H5 gamewebUrl: "http://127.0.0.1:8088/wwz/h5_ad_demo.html",// Attribute allowthirdpartycookies, indicates whether cookies can be delivered in cross-domain mode.// If you need login Google Account or Other Account, Please set TRUE.allowThirdPartyCookies: true,//Attribute fullscreendirection,controls the direction when the webpage requests full screen.//If you want the full screen orientation to be vertical, please set it to portrait. //The default value is landscapefullscreenDirection: "landscape",//If you want the ads in the game to be opened in the browser, please set the value of openMultiwindow// to true and the value of linkJumpPolicy to browserlinkJumpPolicy: "default",openMultiwindow: false,// Here the whitelist settings, when the loading page has multiple addresses, such as the successful loading of the login address and the inconsistent entry address, it needs to set the whitelist to do so.list: ["new RegExp('https?.*')"],},onInit: function () {console.info("onInit");//当前快应用框架只支持在onInit函数中创建广告对象,暂不支持在onMessage等函数中创建,请保持该块代码位置不变nativeAd = ad.createNativeAd({ adUnitId: this.native.adUnitId })rewardedVideoAd = ad.createRewardedVideoAd({ adUnitId: this.rewarded.adUnitId })},onPageStart(e) {console.info('pagestart: ' + e.url)},// Each page switch triggersonPageFinish(e) {console.info('pagefinish: ' + e.url, e.canBack, e.canForward)},onTitleReceive(e) {this.title = e.title;},onError(e) {console.info('pageError : ' + e.errorMsg)},onMessage(e) {console.info('onmessage e = ' + e.message + ", url = " + e.url);prompt.showToast({message: e.message + ': ' + e.url})var msg=e.message;if(msg==='requestNativeAd'){if(this.isSupportAd()){this.requestNativeAd();}}else if(msg==='requestRewardAd'){if(this.isSupportAd()){this.requestRewardedAd();}  }else if(msg==='reqReportNativeAdShow'){this.reportNativeShow();}else if(msg==='reqReportNativeAdClick'){this.reportNativeClick();}},isSupportAd:function(){let provider = ad.getProvider();if(provider==='huawei'){return true;}return false ; },requestNativeAd() {console.info("requestNativeAd");nativeAd.onLoad((data) => {console.info('nativeAd data loaded: ' + JSON.stringify(data));this.native.adData = data.adList[0];if (this.native.adData) {let nativeAdObj={"nativeAdData":data};let nativeAdMsg=JSON.stringify(nativeAdObj);console.info("requestNativeAd onload nativeAdMsg= "+nativeAdMsg);let senddata={"message":nativeAdMsg};this.$element('web').postMessage(senddata);}})nativeAd.onError((e) => {console.error('load ad error:' + JSON.stringify(e));let nativeAdErrorObj={"nativeAdDataError":e};let nativeAdErrorMsg=JSON.stringify(nativeAdErrorObj);console.info("requestNativeAd onError nativeAdErrorMsg= "+nativeAdErrorMsg);let errordata={"message":nativeAdErrorMsg};this.$element('web').postMessage(errordata);})nativeAd.load()},reportNativeShow() {nativeAd.reportAdShow({ 'adId': this.native.adData.adId })},reportNativeClick() {nativeAd.reportAdClick({ 'adId': this.native.adData.adId })},requestRewardedAd() {console.info("requestRewardedAd");/**设置广告加载成功回调,然后调用广告show方法展示广告 */rewardedVideoAd.onLoad(() => {console.info("rewarded video ad onLoad");rewardedVideoAd.show();})rewardedVideoAd.offLoad(() => {console.info("rewarded video ad offLoad");})/**监听激励视频广告错误事件。 */rewardedVideoAd.onError((e) => {console.error('load rewarded video ad error:' + JSON.stringify(e));this.rewarded.errStr = JSON.stringify(e)})/**监听激励视频广告关闭事件 */rewardedVideoAd.onClose(() => {console.info("rewarded video ad onClose");})rewardedVideoAd.load();},onDestroy() {nativeAd && nativeAd.destroy()rewardedVideoAd && rewardedVideoAd.destroy()},isCanForward() {this.$element('web').canForward({callback: function (e) {if (e) {this.$element('web').forward();}}.bind(this)})},isCanBack() {this.$element('web').canBack({callback: function (e) {if (e) {this.$element('web').back();} else {router.back();}}.bind(this)})},onShow: function () {console.info("onshow");},onHide: function () {console.info("onHide");},onBackPress() {this.isCanBack();return true}}
</script>

更多广告接入FAQ和案例请参见:

https://developer.huawei.com/consumer/cn/doc/development/quickApp-Guides/quickapp-access-ads-kit

下附为示例HTML文件:

<!-- saved from url=(0060)file:///C:/Users/L00504~1/AppData/Local/Temp/h5_ad_demo.html -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>ad Demo</title><meta name="viewport" content="width=device-width, initial-scale=1"><style>table.dataintable {margin-top:10px;border-collapse:collapse;border:1px solid #aaa;width:100%;}table.dataintable th {vertical-align:baseline;padding:5px 15px 5px 6px;background-color:#d5d5d5;border:1px solid #aaa;text-align:left;}table.dataintable td {vertical-align:text-top;padding:6px 15px 6px 6px;background-color:#efefef;border:1px solid #aaa;}</style><script language="javascript">system.onmessage = function(data) {console.info("onmessage data="+data);setResult(data);var adDataObject=JSON.parse(data);if(adDataObject.nativeAdData){var nativeAdList=adDataObject.nativeAdData.adList[0];if(nativeAdList){if (nativeAdList.imgUrlList) {var imgSrc=nativeAdList.imgUrlList[0];document.getElementById("adImage").src= imgSrc;console.info('ad data adImgSrc: ' +imgSrc);} }}       }function reportNativeShow() {system.postMessage("reqReportNativeAdShow"); }function reportNativeAdClick() {console.info("reportNativeAdClick");system.postMessage("reqReportNativeAdClick"); }function getNativeAd(){system.postMessage("requestNativeAd");}function getRewardAd(){system.postMessage("requestRewardAd");}function setResult(str) {document.getElementById("nativeAdDataResult").innerHTML= str}function setResultnew(str) {document.getElementById("resultnew").innerHTML= str}function onLoadSuc(){console.info("onLoadSuc");reportNativeShow();}function openNewWeb(){system.go("https://www.huawei.com")}function openNewWindow(){window.open("http://www.w3school.com.cn")}</script></head>
<body>
<p>H5 ad demo
</p>
<p>ResultNativeAd: <br> <span id="nativeAdDataResult" style="height:100px;">(unknown)</span>
</p>
<p>ResultRewardAd: <br> <span id="resultnew" style="height:100px;">(unknown)</span>
</p><hr style="height:3px;border:none;border-top:3px double red;">
<p><button onclick="getNativeAd()">Native Ad</button></p>
<hr style="height:3px;border:none;border-top:3px double red;"><p><button onclick="getRewardAd()">Reward Ad</button></p>
<hr style="height:3px;border:none;border-top:3px double red;"><p><img src="file:///C:/i/eg_tulip.jpg" id="adImage" alt="test ad" onclick="reportNativeAdClick()" onload="onLoadSuc()"></p><hr style="height:3px;border:none;border-top:3px double red;">
<p></p></body></html>

原文链接:https://developer.huawei.com/consumer/cn/forum/topic/0204404950119480220?fid=18

原作者:Mayism

华为H5快游戏如何接入广告服务相关推荐

  1. 华为正式推出快游戏,Cocos 率先支持

    华为快游戏正式发布,进一步推动了小游戏生态的发展! 2018 年 12 月 25 日,华为宣布其 2018 年智能手机出货量成功将突破两亿台,为 2018 年的表现画上了一个辉煌的句号. 庞大的出货量 ...

  2. h5 nan_手把手教你将H5游戏打包成快游戏

    H5游戏可以通过快应用的web组件快速打包成快游戏,打包上架后的快游戏,只要原H5游戏的url不发生变动,快游戏就不需要做更新,维护工作量小. 使用快应用IDE,打包快游戏的操作很简单. 访问官网安装 ...

  3. 华为快游戏调用登录接口失败,返回错误码 -1

    问题描述 在快游戏项目中,调用华为提供的登录接口,按照示例代码编写完成后,在手机上调试登录时,返回错误码 -1.如下: I jsLog : gameLoginWithReal fail:"A ...

  4. 使用SDK快速接入各大平台快游戏 微信小游戏 QQ小游戏使用方法-附源码下载地址

    使用SDK快速接入各平台快游戏 微信小游戏 QQ小游戏 使用方法 引入SDK文件 // 该方式引入可以直接使用qgsdk<script src="qg-sdk.min.1.0.4.js ...

  5. LayaAir2.8新增适配华为快游戏!

    为了让开发者尽快的体验到华为快游戏,我们在LayaAir 2.8.0正式版之前,追加了华为快游戏的适配,提前推出支持华为快游戏LayaAir 2.8.0beta2版本. 华为快游戏平台简介 快应用是一 ...

  6. 快应用如何接入微信支付

    微信APP支付: 如果之前没有在android端接入过微信支付,建议先看看 微信官方文档 , 快应用接入微信App支付的过程和这个流程介绍中的一致,无非是发起的客户端由android app变成了快应 ...

  7. 教你一招H5快应用快速回到首页

    使用快应用web组件打包封装成H5快应用后,原网页自身没有提供返回主页的功能,但转成快应用后,希望用户在浏览任一H5页面时,都能有一个回到网页主页的入口. 此需求可以参考如下步骤实现. 在页面scri ...

  8. 取代Flash的HTML5技术( H5 编写游戏的优点)

    什么是Flash     Flash 是由 Adobe 公司开发的一种富媒体技术,起初是一种放置在浏览器中的插件,填补了当时 HTML 页面平淡的空白,增强了网页交互的能力.你可以在 Flash 中做 ...

  9. “倔驴”一个h5小游戏的实现和思考(码易直播)——总结与整理

    3月23日晚上8点半(中国队火拼韩国的时候),做了一期直播分享.15年做的一个小游戏,把核心代码拿出来,现场讲写了一遍,结果后面翻车了,写错了两个地方,导致运行效果有点问题,直播边说话边写代码还真不一 ...

最新文章

  1. AXM-Net:用于行人检测的跨模式上下文注意力网络
  2. 支持实践教学:清华大数据能力提升项目举办CIKM AnalytiCup2017冠军团队经验分享会
  3. Exchange Server 2003多服务器安装以及管理工具介绍
  4. Oracle EBS:Package被锁,执行时卡住的解决办法
  5. MySQL 错误 #1113
  6. jquery.treeview.js php mysql,jquery.treeview应用
  7. 多网卡Iptables端口转发
  8. 1.1.2 Greedy Gift Givers 贪婪的送礼者
  9. win10下装黑苹果双系统_预算5000的黑苹果/WIN双系统台式电脑组装建议
  10. 威联通+nas+mysql_让不同品牌的 NAS 没有距离,群晖和威联通之间如何同步
  11. 《论个人在历史上的作用》总结反思
  12. android图片自动翻转,android图片翻转镜像
  13. 实时股票行情接口api有哪些?
  14. 代数结构与有限域之 群
  15. 自协方差函数的Matlab实现
  16. 数字孪生 软著登记表 模板
  17. 潜入浅出,java多线程到底是个什么东东?面试中应该注意哪方面多线程的知识?
  18. 用计算机专业怼人,专业示范,教你如何用所学专业知识“怼人”
  19. 超实用后台UI模板有这些就够了!(一)
  20. Ubuntu查找软件命令

热门文章

  1. Jmeter自定义函数开发-------输入参数被分割
  2. 麻省理工学院:科技宠儿的摇篮
  3. 我也可以很极地很阳光
  4. 苹果手机计算机软件不见了怎么办,苹果通讯录怎么不见了?苹果通讯录没了怎么办...
  5. Java总结之基础篇
  6. nsga 的java实现_Java – Scala遗传算法(GA)库中的模拟二进制交叉(SBX)交叉运算符
  7. 7. django应用及分布式路由
  8. try anbox or waydroid (by quqi99)
  9. java画笑脸_canvas画笑脸
  10. 用python计算100以内所有奇数的和_python如何求1到100的奇数和