【问题标题】:Load External Script From Advertising Partner in React.js app在 React.js 应用程序中从广告合作伙伴加载外部脚本
【发布时间】:2020-04-05 00:02:53
【问题描述】:

我想在我的 React.js Web 应用中包含两种类型的广告

<script async="async" data-cfasync="false" src="//somewebstite.com/invoke.js"></script>
<div id="container-4foobarbaz"></div>

还有这个广告:

<script type="text/javascript">
atOptions = {
    'key' : 'somekey',
    'format' : 'iframe',
    'height' : 250,
    'width' : 300,
    'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.cdnwebsite.com/invoke.js"></scr' + 'ipt>');

如何在我的 React 应用程序中包含它? 我尝试了一些方法,但都没有奏效,包括:

    const script = document.createElement("script");
    script.async = true;
    script["data-cfasync"] = true;
    script.src = "//somewebstite.com/invoke.js"

    this.div.appendChild(script); 

渲染中的这个:

<div id="container-4foobarbaz" ref={el => (this.div = el)} >

  </div> 

【问题讨论】:

    标签: javascript html reactjs ads external-script


    【解决方案1】:

    我看到您正在尝试使用 adsTerra,所以这是一个工作示例(在 Typecript 中)

    import { useEffect, useRef } from 'react'
    export default function Banner(): JSX.Element {
        const banner = useRef<HTMLDivElement>()
    
        const atOptions = {
            key: 'YOUR_KEY',
            format: 'iframe',
            height: 50,
            width: 320,
            params: {},
        }
        useEffect(() => {
        if (!banner.current.firstChild) {
            const conf = document.createElement('script')
            const script = document.createElement('script')
            script.type = 'text/javascript'
            script.src = `//www.highperformancedformats.com/${atOptions.key}/invoke.js`
            conf.innerHTML = `atOptions = ${JSON.stringify(atOptions)}`
    
            if (banner.current) {
                banner.current.append(conf)
                banner.current.append(script)
            }
        }
    }, [])
    
        return <div ref={banner}></div>
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用此示例代码。这背后的想法是在安装组件并初始化广告时导入广告脚本。每次组件重新挂载到 DOM 时,它都不会导入已经导入的广告脚本。我还在 Codesandbox 上为您创建了一个示例:https://codesandbox.io/s/example-react-google-ads-0b700

        componentDidMount() {
          // inject some code to head element
          const head = document.querySelector("head");
          // import google ads script if not yet imported
          if (!head.querySelector("#my-google-ads-1")) {
            const script = document.createElement("script");
            script.id = "my-google-ads-1";
            script.async = true;
            script.src = "https://www.google.com/adsense/search/ads.js";
            head.appendChild(script);
          }
          // add another script to head element
          if (!head.querySelector("#my-google-ads-2")) {
            const script = document.createElement("script");
            script.id = "my-google-ads-2";
            script.type = "text/javascript";
            script.charset = "utf-8";
            script.innerHTML = `
              (function(g,o){g[o]=g[o]||function(){(g[o]['q']=g[o]['q']||[]).push(
              arguments)},g[o]['t']=1*new Date})(window,'_googCsa');
            `;
            head.appendChild(script);
          }
      
          // init ads
          var pageOptions = {
            "pubId": "pub-9616389000213823", // Make sure this the correct client ID!
            "query": "hotels",
            "adPage": 1
          };
      
          var adblock1 = {
            "container": "afscontainer1",
            "width": "700",
            "number": 2
          };
      
          window._googCsa('ads', pageOptions, adblock1);
        }
      
        render() {
          return (
            <div className="App">
              <h1>Hello React.js</h1>
              <h2>These are sample ads</h2>
              <div id='afscontainer1'></div>
            </div>
          );
        }
      

      【讨论】:

      • 如果我使用的是谷歌以外的提供商怎么办?我的供应商是 Adsterra。以下调用window._googCsa('ads', pageOptions, adblock1); 的等效项是什么
      • 您可以查看提供商网站上的文档并将我的示例代码修改为您的。通常所有提供商都要求我们导入库并初始化广告。
      猜你喜欢
      • 2021-09-04
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 2021-07-20
      • 2017-07-27
      相关资源
      最近更新 更多