ad.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const adChace = {}
  2. const adUnitIds = [
  3. 'adunit-43f0133726683dec',
  4. 'adunit-e0d329fbf15baad3',
  5. 'adunit-d4d828a7202aa659',
  6. 'adunit-77f75ec31751b42c',
  7. 'adunit-776e9695447f0bd9',
  8. 'adunit-731499e60b328a41',
  9. 'adunit-92daaea26f101651',
  10. 'adunit-e1e0fa16d8157808',
  11. 'adunit-85594f587d807fbe',
  12. 'adunit-40d51a741c1d1342',
  13. ]
  14. export default function ad(config) {
  15. if (wx.getSystemInfoSync().platform === 'devtools') {
  16. return Page(config)
  17. }
  18. const { onLoad, onUnload } = config
  19. let timeout = null
  20. config.onLoad = function() {
  21. let interstitialAd = adChace[this.route]
  22. if (onLoad) onLoad.call(this)
  23. if (wx.createInterstitialAd && !interstitialAd) {
  24. interstitialAd = wx.createInterstitialAd({
  25. adUnitId: adUnitIds[Math.floor(Math.random() * adUnitIds.length)],
  26. })
  27. interstitialAd.onLoad(() => {
  28. console.log(`%c ${this.route} - ad: onLoad event emit`, 'color: #1890ff')
  29. })
  30. interstitialAd.onError((err) => {
  31. console.log(`%c ${this.route} - ad: onError event emit`, 'color: #1890ff', err)
  32. })
  33. interstitialAd.onClose((res) => {
  34. console.log(`%c ${this.route} - ad: onClose event emit`, 'color: #1890ff', res)
  35. })
  36. }
  37. this.showInterstitialAd = this.showInterstitialAd || function() {
  38. if (interstitialAd) {
  39. timeout = setTimeout(() => {
  40. interstitialAd.show().catch((err) => {
  41. console.error(`${this.route} - ad: onShow event emit`, err)
  42. })
  43. }, 3000)
  44. }
  45. }
  46. this.showInterstitialAd.call(this)
  47. }
  48. config.onUnload = function() {
  49. if (onUnload) onUnload.call(this)
  50. if (timeout) {
  51. clearTimeout(timeout)
  52. timeout = null
  53. }
  54. }
  55. return Page(config)
  56. }