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

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

相关文档广告相关事件重复注册

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])

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

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])

其它需要注意的点

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)
    }
}

云衔科技是一家专注于企业数字化广告营销解决方案的服务商。公司凭借深厚的行业经验和专业技术能力,致力于为企业客户提供全方位、更高效的数字化广告营销与运营服务。

发表回复