I've already tried to put it as custom directive, but JS reject script tag in any strings (unterminated literal string). Also, vue-google-adsense and vue-adsense plugins doesn't work for me, because they don't get all parameters that Adsense gives, so ads becomes not responsive etc.
Asked
Active
Viewed 1.4k times
12
-
Have a look here, maybe it can help: https://stackoverflow.com/questions/6197768/dynamic-adsense-insertion-with-javascript/15841383#15841383 – Ren Feb 17 '19 at 11:31
-
Thank you, but I've seen it before :( – Andrew Feb 17 '19 at 18:39
-
I used vue-meta and it works great for me. Article: https://www.the-koi.com/projects/a-step-by-step-guide-on-integrating-google-adsense-into-vout-vue-project/ – alexcodes Feb 23 '22 at 13:19
1 Answers
13
In the index.html
file, add the adsense code out of the #app :
<div id="app"></div>
<div id="divadsensedisplaynone" style="display:none;">
<!-- put here all adsense code -->
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxxxxx"
data-ad-slot="xxxxxx"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
In your main App.vue
or any Vue file, add this where you want the ad to be shown (you are free to change the style) :
<div id="adsgoeshere" style="background: #1d1f29; padding-top:60px; text-align: center;" v-html="adsenseContent"></div>
In the data
add :
adsenseContent: ''
Finally, in the mounted
function, add :
this.adsenseContent = document.getElementById('divadsensedisplaynone').innerHTML
And that's it ! You don't need any library.

JeffProd
- 3,088
- 1
- 19
- 38
-
It throws this:adsbygoogle.js:1 Uncaught H message: "adsbygoogle.push() error: Fluid responsive ads must be at least 250px wide: availableWidth=0" :( – Andrew Feb 17 '19 at 18:11
-
Try with a banner non responsive but fixed size like horizontal banner 320x50 – JeffProd Feb 17 '19 at 18:25
-
Probably it will work, but I need responsive ad. I tried to make style of divadsensedisplaynone div equal to "visibility: hidden", and it started to work! Buuut... I had two banners - one on the top of the page, and one in place where I added it :D I am close to giving up with this because I lost at least two days on it. This is stupid – Andrew Feb 17 '19 at 18:37
-
I spent a lot of time too. I don't understand why adsense JS code is so poor with many document.write() and no Vue.JS support. Sorry it doesn't work for you. – JeffProd Feb 17 '19 at 18:40
-
-
-
You can simply assign the style to a CSS class as a `computed` property and return the correct height and/or width accordingly, or assign it with JS on `mounted()` with something like `element.style.minHeight = '22px !important'` – d0st Jun 01 '21 at 12:15