Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - How to embed Google Ad Sense into React Component?

The question at hand deals with Google Ad Sense specifically but could apply to any script tag insert. I don't understand how I could add something like this to my component.

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
                            <!-- My Ad-->
                            <ins class="adsbygoogle"
                                 style="display:block"
                                 data-ad-client="ca-pub-24524524"
                                 data-ad-slot="152452452"
                                 data-ad-format="auto"></ins>
                            <script>
                            (adsbygoogle = window.adsbygoogle || []).push({});
                            </script>

Is something like this even possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A third party script should not be necessary for something like this.

Ad-Sense requires a third party script that looks like this, this should be loaded prior to react and or just put into a template if you're using any sort of template (i.e... django template etc...)

put this in template:

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

then take your ad sense include, remove the comment (assuming you're using JSX) and turn what google gave you

what google gave you:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> 
<!-- yourAdname-->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-23452425"
     data-ad-slot="24524524"
     data-ad-format="auto">
</ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

change it to this:

<ins className="adsbygoogle"
     style={{display:'block'}}
     data-ad-client="ca-pub-23452425"
     data-ad-slot="24524524"
     data-ad-format="auto">
</ins>

then put the actual execution code in the componentDidMount function

(adsbygoogle = window.adsbygoogle || []).push({});

I would imagine a similar solution would work for just about any of the same circumstances, not just Ad-Sense.

One common misconception is that people often think they can put a script tag in a dangerouslySetInnerHTML attribute and that is not the case. It's using setInnerHTML which will not execute script tags.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...