下面将详细介绍在uni-app中插入广告的具体步骤:
-
开通广告
- 操作平台后台:首先需要在广告平台的后台进行开通操作。对于App平台、H5平台及微信小程序平台,需要在这些平台的管理后台进行相应的操作[1]。
- 其他小程序平台:在其他小程序平台上,例如支付宝小程序、百度小程序等,则需要在各自的小程序管理后台操作[1]。
-
编写代码
- 选择合适位置:在页面的合适位置编写代码,放置广告组件,并配上广告位id。以下是一个简单的示例:
<template> <view class="content"> <view class="ad-view"> <ad adpid="1111111111" @load="onload" @close="onclose" @error="onerror"></ad> </view> </view> </template>
- 事件处理:在脚本部分添加事件处理函数,例如
onload
、onclose
和onerror
,以便处理广告的加载、关闭和错误事件:onload(e) { console.log("onload"); }, onclose(e) { console.log("onclose: " + e.detail); }, onerror(e) { console.log("onerror: " + e.detail.errCode + " message:: " + e.detail.errMsg); }
- 选择合适位置:在页面的合适位置编写代码,放置广告组件,并配上广告位id。以下是一个简单的示例:
-
封装广告功能
- 创建Utils.js文件:为了减少重复代码,可以将插屏广告和激励广告的功能封装到一个独立的JS文件中,例如命名为
Utils.js
。在该文件中定义两个对象interstitial
和rewarded
,分别用于处理插屏广告和激励广告的逻辑[3][5]。 - 插屏广告封装:
var interstitialAd = null; let interstitial = { load(id) { if (uni.createInterstitialAd) { interstitialAd = uni.createInterstitialAd({ adUnitId: id }); interstitialAd.onLoad(() => { console.log('插屏广告加载中'); }); interstitialAd.onError((err) => { console.log('加载错误', err); }); interstitialAd.onClose((res) => { console.log('插屏广告关闭', res); }); } }, show() { if (interstitialAd) { interstitialAd.show().catch((err) => { console.error(err); }); } } };
- 激励广告封装:
var videoAd = null; let rewarded = { load(id, e) { if (uni.createRewardedVideoAd) { videoAd = uni.createRewardedVideoAd({ adUnitId: id }); videoAd.onError(err => {}); videoAd.onClose((status) => { if (status && status.isEnded || status === undefined) { e(); } else {} }); } }, show() { if (videoAd) { videoAd.show().catch(() => { // 失败重试 videoAd.load() .then(() => videoAd.show()) .catch(err => { console.log('激励视频 广告显示失败'); }); }); } } };
- 导出封装对象:最后将这些封装好的对象导出,以供其他页面调用:
module.exports = { interstitial, rewarded };
- 创建Utils.js文件:为了减少重复代码,可以将插屏广告和激励广告的功能封装到一个独立的JS文件中,例如命名为
-
导入并使用封装的广告功能
- 导入Utils.js:在需要调用广告的页面导入之前封装好的
Utils.js
文件,注意文件的相对路径不要写错[3][5]。import Utils from '../../utils/Utils.js';
- 加载并展示广告:在页面的生命周期函数或适当的时机调用封装好的广告方法。例如在
onLoad
方法中加载插屏广告和激励广告,并在需要显示的时候调用show
方法[3][5]。onLoad() { // 加载插屏广告 Utils.interstitial.load('你的广告id'); // 加载激励广告 Utils.rewarded.load('adunit-85e98527c651f48f', () => { // 这里写你的任意奖励事件 }); }, someFunctionToShowAds() { // 展示插屏广告 Utils.interstitial.show(); // 展示激励广告 Utils.rewarded.show(); }
- 导入Utils.js:在需要调用广告的页面导入之前封装好的
通过以上步骤,可以在uni-app项目中有效地插入和管理各种类型的广告。这些步骤不仅涵盖了基本的代码实现,还提供了封装广告功能的高级技巧,以简化代码结构并提高可维护性。