How to add google adsense to vuejs component

This is a sample google adsense script code.

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- my ad unit -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-8110153470270370"
     data-ad-slot="1575866657"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Let’s see how to add this to vuejs component.

1.) Add google adsense javascript url into html head.

<head>
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
</head>

2.) Add following code into html template section in vuejs component.

<template>
    <div class="your-page">
        <div class="section">
            <div class="container">
                <ins class="adsbygoogle"
                     style="display:block"
                     data-ad-client="ca-pub-8110132270270370"
                     data-ad-slot="4824315952"
                     data-ad-format="auto"
                     data-full-width-responsive="true"></ins>
            </div>
        </div>
    </div>
</template>

3.) Then, add following adsenseAddLoad() function into methods section and call it within mounted() section.

mounted () {
    this.adsenseAddLoad();
},

methods:{
    adsenseAddLoad(){
        let inlineScript   = document.createElement("script");
        inlineScript.type  = "text/javascript";
        inlineScript.text  = '(adsbygoogle = window.adsbygoogle || []).push({});'
        document.getElementsByTagName('body')[0].appendChild(inlineScript);
    }
}

Done! Now refresh your vuejs component.

2 thoughts on “How to add google adsense to vuejs component”

Leave a Comment