Google AdSenseをReactに対応させる
Reactで作ったwebページに対してGoogle AdSenseを表示させる機会があり、その際に少し手こずったので、対応方法について書く。
まず前提条件として、下記のscriptをheadタグ内に設定しておく。
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
Reactを使わなければinsタグとscriptタグを設定することで表示させることができる。
<ins class="adsbygoogle" data-ad-client="ca-pub-XXX" data-ad-slot="XXX" ></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script>
まずはじめにReactのrenderメソッドにすべて入れてみた。
class GoogleAdsense extends React.Component { constructor(props) { super(props); } render(){ return ( <ins class="adsbygoogle" data-ad-client="ca-pub-XXX" data-ad-slot="XXX" ></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> ); } }
単純にrenderメソッドの中に全部入れただけでは、正常に表示させることはできなかった。
そこで、scriptの部分をcomponentDidUpdateメソッドに移動させた。
class GoogleAdsense extends React.Component { constructor(props) { super(props); } componentDidUpdate(prevProps, prevState, snapshot){ window.adsbygoogle = window.adsbygoogle || []; window.adsbygoogle.push({}); } render(){ return ( <ins class="adsbygoogle" data-ad-client="ca-pub-XXX" data-ad-slot="XXX" ></ins> ); } }
componentDidUpdateメソッドの中に移動させることによって、updateされる度にgoogle adsenseのjsが呼び出されればいいなぁ〜と淡い期待で組んだところエラーが発生。
adsbygoogle.push() error: All ins elements in the DOM with class=adsbygoogle already have ads in them.
調査してみると、一度、adsbygoogleのpushメソッドをコールした場合、再度、呼び出してしまうとエラーになってしまうようだ。
そこで、一回だけ実行すればいいことがわかったので、componentDidMountメソッドに移動させた。
class GoogleAdsense extends React.Component { constructor(props) { super(props); } componentDidMount(){ window.adsbygoogle = window.adsbygoogle || []; window.adsbygoogle.push({}); } render(){ return ( <ins class="adsbygoogle" data-ad-client="ca-pub-XXX" data-ad-slot="XXX" ></ins> ); } }
無事に表示させることができた。
adsbygoogle.pushメソッドを何回も呼び出すとエラーになってしまうのは知らないと気がつかないので、今度から実装する時は意識したい。