Search code examples
reactjsjsxgatsby

Add Script tag in Gatsby


I have created a Gatsby website. To enable push notification in that website I have to use this code:

<!-- Begin DigitalPUSH code -->
<script>
var DGPkey = "M3E2cGU5d1hPQWl2VTRTeG9ZYU8xa0l1YW8yMWVmR3FKbFFjMGNLNllIbz0="; //mandatory
var DGPnativerequest = "0";
var DGPdelay = "10000";
var DGPmtype = "overlay";
var DGPtheme = "13e3b4";
var DGPtitle = "!!!  !!!";
var DGPmessage = "!!!  !!!";
var DGPallowbutton = "";
var DGPrejectbutton = "";
var DGPbgimage = "";
var DGPinpageads = "0";
</script>
<script type="text/javascript" src="//cdn.digitalpush.org/lib.js"></script>
<!-- End DigitalPUSH code -->

I have to put this code before the tag. I tried couple of methods from the internet but none seem to work. Can someone please tell me how to do this?

My website's template:https://github.com/Tahsin007/classsed-gatsby-blog

Thanks in advance.


Solution

  • 2022 update

    Since the release of the Script Gatsby component (powered by Partytown) it's much easier adding third-party scripts. Just:

    import React from "react"
    import { Script } from "gatsby"
    
    function YourPage() {
      return <Script src="https://my-example-script" />
    }
    
    export default YourPage
    

    From what is extracted from Gatsby documentation about using client-side packages/librares. I would suggest the following.

    With React (and also with Gatsby) you can easily achieve this by using <Helmet> tag. Basically, it allows you to put <scripts> (or other metadata) in any component which will be placed in the <head> once compiled. So, in your case:

        import React, {useEffect} from "react"
        import Helmet from "react-helmet"
        
        import Layout from "../components/layout"
        import SEO from "../components/seo"
    
        const AnyPage = () => (
        useEffect(()=>{
        var DGPkey = "M3E2cGU5d1hPQWl2VTRTeG9ZYU8xa0l1YW8yMWVmR3FKbFFjMGNLNllIbz0=";
        var DGPnativerequest = "0";
        var DGPdelay = "10000";
        var DGPmtype = "overlay";
        var DGPtheme = "13e3b4";
        var DGPtitle = "!!!  !!!";
        var DGPmessage = "!!!  !!!";
        var DGPallowbutton = "";
        var DGPrejectbutton = "";
        var DGPbgimage = "";
        var DGPinpageads = "0";
    },[])
            return <Layout>
              <SEO title="AnyPage" />
              <Helmet>
                <script src="//cdn.digitalpush.org/lib.js"/>
              </Helmet>
            <div>Dummy content</div>
            </Layout>
        )
        
        export default AnyPage
    

    You can find more information about <Helmet> tag and its usage in their documentation.

    Here's a screenshot testing in my local machine:

    enter image description here