Kaherdin
Kaherdin

Reputation: 2127

Integrate external script to nextJS

I want to integrate a script from marker.io to my nextJS app, it should be loaded on every page, here is the snippet :

<script>
  window.markerConfig = {
    destination: 'mykeysecret', 
    source: 'snippet'
  };
</script>

<script>
!function(e,r,a){if(!e.__Marker){e.__Marker={};var t=[],n={__cs:t};["show","hide","isVisible","capture","cancelCapture","unload","reload","isExtensionInstalled","setReporter","setCustomData","on","off"].forEach(function(e){n[e]=function(){var r=Array.prototype.slice.call(arguments);r.unshift(e),t.push(r)}}),e.Marker=n;var s=r.createElement("script");s.async=1,s.src="https://edge.marker.io/latest/shim.js";var i=r.getElementsByTagName("script")[0];i.parentNode.insertBefore(s,i)}}(window,document);
</script>

I try to use the nextjs built-in <Script ... /> feature, but I didn't manage to make it works.

Upvotes: 0

Views: 639

Answers (2)

Olivier Kaisin
Olivier Kaisin

Reputation: 529

Since Marker.io doesn't provide a dedicated Next.js plugin (yet), the recommended way to integrate it is by using the dangerouslySetInnerHTML attribute from the <Script> component.

Example:

<Script
  strategy="beforeInteractive"
  dangerouslySetInnerHTML={{
    __html: `
    window.markerConfig = {
      destination: '<REPLACE_ME>', 
      source: 'snippet'
    };

    !function(e,r,a){if(!e.__Marker){e.__Marker={};var t=[],n={__cs:t};["show","hide","isVisible","capture","cancelCapture","unload","reload","isExtensionInstalled","setReporter","setCustomData","on","off"].forEach(function(e){n[e]=function(){var r=Array.prototype.slice.call(arguments);r.unshift(e),t.push(r)}}),e.Marker=n;var s=r.createElement("script");s.async=1,s.src="https://edge.marker.io/latest/shim.js";var i=r.getElementsByTagName("script")[0];i.parentNode.insertBefore(s,i)}}(window,document);
  `,
  }}
/>

Useful links:

Upvotes: 2

Abdellah Sabiri
Abdellah Sabiri

Reputation: 396

There is another way of injecting script with dangerouslySetInnerHTML:

    <script
       dangerouslySetInnerHTML={{
          __html: `!function(e,r,a){if(!e.__Marker){e.__Marker={};var t=[],n={__cs:t};["show","hide","isVisible","capture","cancelCapture","unload","reload","isExtensionInstalled","setReporter","setCustomData","on","off"].forEach(function(e){n[e]=function(){var r=Array.prototype.slice.call(arguments);r.unshift(e),t.push(r)}}),e.Marker=n;var s=r.createElement("script");s.async=1,s.src="https://edge.marker.io/latest/shim.js";var i=r.getElementsByTagName("script")[0];i.parentNode.insertBefore(s,i)}}(window,document);`,
       }}
    />

Upvotes: 2

Related Questions