如何在Vue 3及Ionic Vue 3项目中集成实现Google AdSense广告功能
Vue 3 + Ionic 项目 AdSense 集成方案
1. 前期准备
- 先在AdSense后台获取你的发布商ID(格式为
ca-pub-xxxxxxxxxx)和对应场景的广告位ID - 提前在AdSense后台配置好需要的广告类型,比如展示广告、信息流广告等,记录对应参数
2. 全局注入AdSense脚本
无需依赖第三方Vue组件,手动按需注入脚本即可,同时适配多平台场景,避免Android端加载多余资源报错。你可以在根组件App.vue的onMounted生命周期或者main.ts中添加如下逻辑:
// 仅在Web平台运行时加载AdSense脚本 if (typeof window !== 'undefined' && window.location.protocol === 'https:') { const script = document.createElement('script') // 替换为你自己的发布商ID script.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-你的发布商ID' script.async = true script.crossOrigin = 'anonymous' document.head.appendChild(script) // 挂载全局变量用于后续广告推送 window.adsbygoogle = window.adsbygoogle || [] }
注意本地http开发环境广告不会正常加载,属于正常现象,部署到https线上环境即可恢复
3. 封装通用AdSense复用组件
自己封装Vue3组件适配Ionic的路由逻辑,方便多个页面调用:
<template> <div v-if="isWebPlatform" class="ads-wrapper"> <ins class="adsbygoogle" :style="{ display: 'block' }" :data-ad-client="adClient" :data-ad-slot="adSlot" :data-ad-format="adFormat" :data-full-width-responsive="fullWidthResponsive" ></ins> </div> </template> <script setup lang="ts"> import { ref, onMounted, watch } from 'vue' import { Capacitor } from '@capacitor/core' // Ionic自带的平台判断工具 const props = defineProps<{ adClient: string adSlot: string adFormat?: 'auto' | 'fluid' | 'rectangle' | 'horizontal' | 'vertical' fullWidthResponsive?: 'true' | 'false' }>() // 默认值配置 withDefaults(props, { adFormat: 'auto', fullWidthResponsive: 'true' }) const isWebPlatform = ref(Capacitor.getPlatform() === 'web') const loadAd = () => { if (isWebPlatform.value && window.adsbygoogle) { try { window.adsbygoogle.push({}) } catch (e) { console.error('广告加载异常', e) } } } onMounted(() => { // 轮询检查脚本加载完成后再推送广告 const checkAdsReady = setInterval(() => { if (window.adsbygoogle) { clearInterval(checkAdsReady) loadAd() } }, 100) }) // 适配Ionic路由切换后重新加载广告的场景 watch( () => window.location.pathname, () => { setTimeout(() => loadAd(), 500) } ) </script> <style scoped> .ads-wrapper { width: 100%; margin: 12px 0; display: flex; justify-content: center; } </style>
4. 业务页面调用组件
在需要展示广告的页面直接引入封装好的组件即可,示例如下:
<template> <ion-page> <ion-content class="ion-padding"> <!-- 你的页面业务内容 --> <AdSense ad-client="ca-pub-你的发布商ID" ad-slot="你的广告位ID" ad-format="auto" full-width-responsive="true" /> </ion-content> </ion-page> </template> <script setup lang="ts"> import AdSense from '@/components/AdSense.vue' </script>
5. 注意事项
- 不要重复加载adsbygoogle脚本,全局仅加载一次即可,避免报错
- 广告位ID需要和AdSense后台创建的广告类型对应,否则会出现展示异常
- 如果路由切换后广告不展示,可以适当调整组件内路由监听的延迟时间
内容的提问来源于stack exchange,提问作者Daniel Viaño
相关产品推荐
相关产品推荐

