Embed <script> tag into React Gatsby Component

Viewed 439

I am trying to embed the podcast player provided by Buzzsprout. This is the code they provide.

<div id="buzzsprout-player-61XX09"></div>
<script src="https://www.buzzsprout.com/14XX79/61XX09-the-podcast-promo.js?container_id=buzzsprout-player-61XX09&player=small" type="text/javascript" charset="utf-8"></script>

The intention is to have multiple players on a single page, a list of podcast episodes. However the above code does not work with a Gatsby component. I've search for ways to include this and unable to find a solution.

I have tried the following but this does not work.

const IndexPage = () => (
<script dangerouslySetInnerHTML={{__html: `src="https://www.buzzsprout.com/14XX79/61XX09-the-podcast-promo.js?container_id=buzzsprout-player-61XX09&player=small" type="text/javascript" charset="utf-8"`}} />
)

Spent a while trying other options such as the react-script-tag package but uses deprecated methods and does not work. Any help would be great!

1 Answers

Use <Helmet> component:

const IndexPage = () => (
<>
  <Helmet>
    <script defer src="https://www.buzzsprout.com/14XX79/61XX09-the-podcast-promo.js?container_id=buzzsprout-player-61XX09&player=small" type="text/javascript" charset="utf-8" />
  </Helmet>
</>
)

Basically, the <Helmet> (imported from react-helmet) component puts inside the head tag everything that has wrapped inside. You may want to play with the defer attribute if needed (thanks @LekoArts for the reference at https://github.com/gatsbyjs/gatsby/discussions/30752).

Keep in mind that with your approach, you are exposing the site to XSS (Cross-Site Scripting) attacks since you are using dangerouslySetInnerHtml (hence the name). You can use some parse libraries to avoid its usage if needed. Using <Helmet> approach your site is completely safe.


The issue has been solved using a native iframe for this use-case.

Related