微信小程序的广告使用踩坑

语言: CN / TW / HK

微信小程序广告接入,相关的文档说的已经很清晰了,下面主要总结了我遇到的一些问题。

相关文档

广告相关事件重复注册

  • 问题代码

```js useEffect(() => { // 拉取插屏广告 if (wx.createInterstitialAd) { interstitialAd.current = wx.createInterstitialAd({ adUnitId: 'adunit-xxxx' })

  // 广告加载调试可打开以下注释代码
  const handleOnLoad = () => {
    console.log('插屏广告拉取成功~~')
  }
  interstitialAd.current.onLoad(handleOnLoad)

  const handleOnError = (err) => {
    console.warn('wx.createInterstitialAd error: ', err)
  }
  interstitialAd.current.onError(handleOnError)

  const handleOnClose = () => {
    // 关闭插屏广告后,播放领取动画
    handleShowDrawDownTips()
  }
  interstitialAd.current.onClose(handleOnClose)
}

}, [handleShowDrawDownTips]) `` 上述代码中的副作用因为依赖了外部传入的方法handleShowDrawDownTips`,当此方法发生变更时,上述副作用会被触发,导致广告被重复注册,相关事件被重复注册。 改进:广告注册逻辑与事件注册分离开,事件注册前先进行销毁(这个操作在微信的文档-广告指南中有提到,但具体方法没有写明,后来谷歌后,在对应的 API 文档中找到了相关方法)

  • 问题处理后

```js useEffect(() => { // 拉取插屏广告 if (wx.createInterstitialAd) { interstitialAd.current = wx.createInterstitialAd({ adUnitId: 'adunit-xxxx' }) } }, [])

useEffect(() => { // 插屏广告添加监听事件 if (interstitialAd.current) { // 广告加载调试可打开以下注释代码 const handleOnLoad = () => { console.log('插屏广告拉取成功~~') } interstitialAd.current.onLoad(handleOnLoad)

  const handleOnError = (err) => {
    console.warn('wx.createInterstitialAd error: ', err)
  }
  interstitialAd.current.onError(handleOnError)

  const handleOnClose = () => {
    // 关闭插屏广告后,播放领取动画
    handleShowDrawDownTips()
  }
  interstitialAd.current.onClose(handleOnClose)

  // 此处取消监听事件
  return () => {
      interstitialAd.current.offLoad(handleOnLoad)
      interstitialAd.current.offError(handleOnError)
      interstitialAd.current.offClose(handleOnClose)
  }

}, [handleShowDrawDownTips])

```

其它需要注意的点

  • 多个可控制播放的广告(激励式视频广告,插屏广告)展示之间需要一定的间隔时间,若间隔时间太短,下一个广告将不会播放
  • 广告可能拉取不到,需要处理好没拉取到广告的相关交互和展示逻辑
  • 某些情况,如触发了频次限制,插屏广告即使加载成功了,调用interstitialAd.current.show()时也不会展示,甚至官方所说的在 catch 也不会执行 ```js if (interstitialAd.current) { interstitialAd.current.show().catch((err) => { 某些情况,如触发了频次限制,插屏广告不展示也不报错,所以不会执行一下逻辑 handleShowDrawDownTips() console.warn('「插屏广告展示出错」error', error) ) }

// 可尝试以下方法做好业务的兜底 if (interstitialAd.current) { // 防止广告因为触发频率限制不展示,导致后续逻辑没有正常执行 const timer = setTimeout(() => { handleShowDrawDownTips() }, 1000)

try {
  await interstitialAd.current.show()
  clearTimeout(timer)
} catch (error) {
  clearTimeout(timer)
  handleShowDrawDownTips()
  console.warn('「插屏广告展示出错」error', error)
}

} ```