How Can I Integrate HUAWEI Ads into a Huawei HTML5 Quick Game?
Symptom:
Currently, no ad API is provided for an HTML5 quick game. How can I integrate HUAWEI Ads into my quick game?
Analysis:
Currently, HUAWEI Ads supports only quick apps and runtime quick games, but not HTML5 quick games. You can use a two-way communication mechanism between the web component on the UX page of a quick game and the HTML5 web page of the game to integrate HUAWEI Ads into an HTML5 quick game. The onMessage lifecycle function on the UX page receives messages from an HTML5 page, calls the ad API of quick apps to obtain ad information (only available for native ads and rewarded video ads), and sends the obtained ad information to the HTML5 page through this.$element(‘web’).postMessage({ message: JSON.stringify(result) });.
Solution:
It is recommended that the ad creation and ad API request processes be separately encapsulated in different functions, instead together in the onInit or onMessage lifecycle function. This is because the onInit function is called during page initialization, which implements quicker loading, but it is not suitable for processing complex logic; the onMessage function is used to receive character strings passed by HTML5 pages. After you add a judgment branch, the corresponding function is called to perform specific ad processing.
Note: Currently, the quick app framework supports the creation of ad objects only in the onInit function, but not in functions such as onMessage. Keep the position of the code block unchanged.
Quick app UX sample code:
<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 nativeAd
let rewardedVideoAd
export default {
props: ['websrc'],
data: {
native: {
adUnitId: 'testu7m3hc4gvm',
adData: {},
errStr: '',
},
rewarded: {
adUnitId: 'testx9dtjwj8hp',
isShow: 'false',
errStr: ''
},
title: "", // TODO Replace the link to the H5 game
webUrl: "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 landscape
fullscreenDirection: "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 browser
linkJumpPolicy: "default",
openMultiwindow: false,
// Here the trustlist 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 trustlist to do so.
list: ["new RegExp('https?.*')"],
},
onInit: function () {
console.info("onInit");
// Currently, the quick app framework supports the creation of ad objects only in the onInit function, but not in functions such as onMessage. Keep the position of the code block unchanged.
nativeAd = ad.createNativeAd({ adUnitId: this.native.adUnitId })
rewardedVideoAd = ad.createRewardedVideoAd({ adUnitId: this.rewarded.adUnitId })
},
onPageStart(e) {
console.info('pagestart: ' + e.url)
},
// Each page switch triggers
onPageFinish(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"); /** Set the callback function for successful ad loading. Call the show method to display ads.*/
rewardedVideoAd.onLoad(() => {
console.info("rewarded video ad onLoad");
rewardedVideoAd.show();
}) rewardedVideoAd.offLoad(() => {
console.info("rewarded video ad offLoad");
}) / ** Listen to rewarded video ad error events. */
rewardedVideoAd.onError((e) => {
console.error('load rewarded video ad error:' + JSON.stringify(e));
this.rewarded.errStr = JSON.stringify(e)
}) /** Listen to rewarded video ad closing events.*/
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>
For more FAQs and cases about HUAWEI Ads integration, visit the following link:
https://developer.huawei.com/consumer/en/doc/development/quickApp-Guides/quickapp-access-ads-kit