简体   繁体   中英

dangerouslySetInnerHTML in react application not working for including Segment.io tags

I am trying to include Segment.io in my react/NextJS app. I am following the convention set by a previous function that sets Google Analytics

const segmentWriteKey = 'xyz';

export default class CustomDocument extends Document {
  setGoogleTags = () => {
    return {
      __html: `
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '${gaTrackingId}');
        console.log('here2');
      `,
    };
  };

  setSegment = () => {
    return {
      __html: `
      !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t,e){var n=document.createElement("script");n.type="text/javascript";n.async=!0;n.src="https://cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(n,a);analytics._loadOptions=e};analytics.SNIPPET_VERSION="4.1.0";
              analytics.load(${segmentWriteKey});
              analytics.page();
              console.log('here1');
      `,
    };
  };

<script
            dangerouslySetInnerHTML={this.setGoogleTags() /* eslint-disable-line react/no-danger */}
          />
          <script
            dangerouslySetInnerHTML={this.setSegment() /* eslint-disable-line react/no-danger */ }
          />

I can see the "here2" being called but never "here1". Any thoughts?

It looks like your function is not closed properly. Two close brackets need to be added to the end of the function inside your __html string:

      ...
      analytics.page();
      console.log('here1');
    };
  };
`,

It's also not clear to me where the ${segmentWriteKey} value is coming from. You may not want the ${} syntax unless you mean to use template literals ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals ). Also, it appears that calling analytics.load() requires two parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM