When I'm trying to add a script on the body of Gatsby I've added the following code into the file called gatsby-ssr.js
const React = require("react")
exports.onRenderBody = ({ setPostBodyComponents }) => {
setPostBodyComponents([
<script type="text/javascript">
{`
(function() {
var envolveChatWidgetScript = document.createElement('script');
envolveChatWidgetScript.setAttribute('data-wg-publisher', '222222');
envolveChatWidgetScript.setAttribute('data-wg-campaign', '333333');
envolveChatWidgetScript.setAttribute('src', 'https://widget.envolvetech.com/static/js/app.js');
envolveChatWidgetScript.setAttribute('data-identifier', 'my_identifier');
envolveChatWidgetScript.setAttribute('data-backend', 'https://bot-dot-envolvetech-001.appspot.com');
document.body.appendChild(envolveChatWidgetScript);
})();
`}
</script>
]);
};
but then somehow what it's actually in the mark up is this
<script type="text/javascript">
(function() {
var envolveChatWidgetScript = document.createElement('script');
envolveChatWidgetScript.setAttribute('data-wg-publisher', '222222');
envolveChatWidgetScript.setAttribute('data-wg-campaign', '3333333');
envolveChatWidgetScript.setAttribute('src', 'https://widget.envolvetech.com/static/js/app.js');
envolveChatWidgetScript.setAttribute('data-identifier', 'my_identifier#x27;);
envolveChatWidgetScript.setAttribute('data-backend', 'https://bot-dot-envolvetech-001.appspot.com');
document.body.appendChild(envolveChatWidgetScript);
})();
</script>
any ideas why it gets translated into that ?
Have you tried customizing the html.js?
Run:
cp .cache/default-html.js src/html.js
Or manually copy the default-html.js (placed inside .cache) to /src
And place your script there.
When Gatsby builds your site if there's a html.js inside /src, it will use it as a boilerplate for your site
In the html.js you'll see all the postBodyComponents, onPreRenderHTML and other customizing APIs. However, in this case, you'll be inserting the raw script instead of allowing Gatsby to parse it.
After reading a few GH threads I found out that adding the script using dangerouslySetInnerHTML actually works https://github.com/gatsbyjs/gatsby/issues/11108
const React = require("react")
exports.onRenderBody = ({ setPostBodyComponents }) => {
setPostBodyComponents([
<script
dangerouslySetInnerHTML={{
__html:`
(function() {
var envolveChatWidgetScript = document.createElement("script");
envolveChatWidgetScript.setAttribute("data-wg-publisher", "222222");
envolveChatWidgetScript.setAttribute("data-wg-campaign", "333333");
envolveChatWidgetScript.setAttribute("src","https://widget.envolvetech.com/static/js/app.js");
envolveChatWidgetScript.setAttribute("data-identifier", "my_identifier");
envolveChatWidgetScript.setAttribute("data-backend", "https://bot-dot-envolvetech-001.appspot.com");
document.body.appendChild(envolveChatWidgetScript);
})();
`
}}
/>,
]);
};