华为快应用、HTML5 和广告

Huawei Quick Apps, HTML5 and Ads

我想在华为HTML5快应用中实现华为广告。我有快应用运行.

请问如何在其中植入Huawei Ads Banner广告?

QuickApp不支持横幅广告,只支持原生广告和激励广告。

HTML5快应用接入广告需要使用与快应用web组件框架的双向通信获取广告

以下是将 HTML5 QuickApp 连接到广告的示例代码。

<template>
    <div class="doc-page">
        <web class="web-page" src="{{webUrl}}" 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 url
            webUrl: "http://xxx/h5_ad_demo.html",
            allowThirdPartyCookies: true,
            fullscreenDirection: "landscape",
            linkJumpPolicy: "default",
            openMultiwindow: false,
            list: ["new RegExp('https?.*')"],
        },
  
        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 = ad.createNativeAd({ adUnitId: this.native.adUnitId })
            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() {
            rewardedVideoAd = ad.createRewardedVideoAd({ adUnitId: this.rewarded.adUnitId });
  
            /**Set the callback function for successful advertisement loading and invoke the ad show method to display the advertisement. */
           rewardedVideoAd.onLoad(() => {
                console.info("rewarded video ad onLoad");
                rewardedVideoAd.show();
            })
  
              rewardedVideoAd.offLoad(() => {
                console.info("rewarded video ad offLoad");
               
            })
  
             /**Listen to the video ad error event. */
            rewardedVideoAd.onError((e) => {
                console.error('load rewarded video ad error:' + JSON.stringify(e));
                this.rewarded.errStr = JSON.stringify(e)
            })
            
           /**Listening for the event of disabling the incentive video ad */
            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>

h5_ad_demo.html

<html>
<head>
    <title>ad Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <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="/i/eg_tulip.jpg"  id="adImage" alt="test ad" onclick="reportNativeAdClick()" onload="onLoadSuc()"/>
 <hr style="height:3px;border:none;border-top:3px double red;" />
</p>
</body>
</html>

详情请参考以下link:

Web component

Accessing HUAWEI Ads Publisher Service