E
E
EvgeniySaschenko2020-12-12 22:00:47
JavaScript
EvgeniySaschenko, 2020-12-12 22:00:47

How to insert adsense ad code into nuxt/vue template?

Good afternoon,

I'm making a site on Nuxt, there is a need to display HTML fragments that come from the backend.

For example, this situation:
I insert such a code using the v-html directive , but the frame with the ad does not appear, but the html that I inserted is simply displayed (that is, the Google script does not see it and does not turn it into a frame).
If the code is simply inserted into the template in a piece, then everything is OK, but it comes in a variable from the backend, so it won’t work out that way.

Perhaps the problem is that the original DOM element (formed based on the response from the server) is replaced by another one, I found this when I searched for the document.querySelector('[data-ad-client]') element in the parent component during the mounted stage .

Plz tell me how to deal with this.

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Homepage Leaderboard -->
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-1234567890123456"
data-ad-slot="1234567890"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
EvgeniySaschenko, 2020-12-20
@EvgeniySaschenko

It didn’t work just to insert the code, I used this vue-google-adsense plugin, got the attribute values ​​​​from the line like this:

const div = document.createElement('div');
div.innerHTML = strHtml;
 const insElement = div.querySelector('ins');
 for (let i = 0; i < insElement.attributes.length; i++) {
    this.insAttr[insElement.attributes[i].name] = insElement.attributes[i].value;
}

J
Just Me, 2020-12-17
@Just__Den

A well-defined problem is rendering dynamic scripts to HTML using JS. Options:
1) insert into a frame. Only not with the help of v-html, but there are native js functions for this. The same can be done with vue - a plugin
2) manually build the script tag and insert it into the HTML

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question