HuaweiH5クイックゲームはどのように広告サービスにアクセスしますか

問題の説明:

H5 Quick Gameには現在、オープンな広告APIインターフェイスがありません。これは、広告サービスへのアクセスを実現する方法です。

問題分析:

現在の広告サービスは、高速アプリとランタイム高速ゲームのみをサポートしています。H5高速ゲームは、広告インターフェイスへの直接アクセスを一時的にサポートしていません。現在、この問題を解決するための一時的なソリューションが提供されています。高速ゲームuxページのWebコンポーネントとゲームH5Webページの間の双方向接続を使用できます。通信機構を実現。uxページのonMessageライフサイクル機能では、H5ページのメッセージを受信し、高速アプリケーションの広告APIインターフェイスにアクセスして広告情報を取得し(ネイティブ広告とリワードビデオ広告のみがサポートされます)、最後に取得した広告情報にthis。$ element( ' web ')。postMessage({message:JSON.stringify(result)}); H5ページに送信します。

解決:

onInitまたはonMessageライフサイクル関数ではなく、広告の作成と要求のプロセス用に別の関数パッケージを作成することをお勧めします。これは、ページの初期化時にonInit関数が呼び出され、読み込み速度が速く、複雑なロジックの処理には適していないためです。onMessage関数はH5 Webページから渡された文字列メッセージを受信し、判断ブランチを追加し、対応する関数を呼び出して、対応する広告処理フローを実行します。

注:現在の高速アプリケーションフレームワークは、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 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 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 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");

            /**设置广告加载成功回调,然后调用广告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

著者:メイズム

おすすめ

転載: blog.51cto.com/14772288/2576873