Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Script tag in Gatsby [closed]

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.

like image 790
Joel007 Avatar asked Mar 03 '23 10:03

Joel007


1 Answers

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

like image 195
Ferran Buireu Avatar answered Mar 05 '23 15:03

Ferran Buireu