あるSEのつぶやき・改

ITやシステム開発などの技術に関する話題を、取り上げたりしています。

Reactでi-mobileの広告を表示する方法

React で i-mobile の広告を表示するのは一筋縄ではいきません。

自分もかなり苦労して広告を表示させることができました。

この記事は、i-mobileから提供されたスクリプトをそのまま使用していますが、ある時点での i-mobile の表示方法であり、将来に渡って広告が表示されることを保証するものではありません。

場合によっては、スクリプト改変と見なされてペナルティを受ける可能性もあります。ですので、あくまで自己責任で行ってください。

また、この記事に関しての質問などの問い合わせも受け付けませんのでご了承ください。

i-mobile の広告スクリプトは、document.write を使用しているため、単純な方法では React で表示することができません。そのため、iframe を用いた方法で広告を表示します。

それでもさらに苦戦させられるのですけどね。。

さて。以下は、i-mobile の広告を表示する React + TypeScript のスクリプトサンプルです。パソコンとスマートフォンで広告の出し分けを行っています。

前述したように質問は受け付けませんので、頑張って読み解いてください。

import React, { useEffect } from 'react';

const AdsCard: React.FC = () => {
  useEffect(() => {
    if(navigator.userAgent.match(/(iPhone|iPad|iPod|Android)/i)){
      // スマホ・タブレット(iOS・Android)の場合の処理を記述
      const div = document.getElementById('ad') as HTMLElement;
      const iframe = document.createElement('iframe');
      div.appendChild(iframe);

      let html = `<body>`;
      html += `<script type="text/javascript">`;
      html += `     imobile_xxxxx = "xxxxx"; `;
      html += `     imobile_xxxxx = "xxxxx"; `;
      html += ` </script>`;
      html += `<script type="text/javascript" src="<script url>"></script>`;
      html += `</body>`;

      const iframeDoc = (iframe.contentWindow as Window).document;
      iframeDoc.open();
      iframe.width = '100%';
      iframeDoc.write(html);
      iframeDoc.close();
    } else {
      // PCの場合の処理を記述
      const div = document.getElementById('ad') as HTMLElement;
      const iframe = document.createElement('iframe');
      div.appendChild(iframe);

      let html = `<body>`;
      html += `<script type="text/javascript">`;
      html += `     imobile_xxxxx = "xxxxx"; `;
      html += `     imobile_xxxxx = "xxxxx"; `;
      html += ` </script>`;
      html += `<script type="text/javascript" src="<script url>"></script>`;
      html += `</body>`;

      const iframeDoc = (iframe.contentWindow as Window).document;
      iframeDoc.open();
      iframe.width = '100%';
      iframeDoc.write(html);
      iframeDoc.close();
    }
  }, []);

  return (
    <div>
      <div id="ad"></div>
    </div>
  );
}

export default AdsCard;