What is this error and how to fix?
data-pterror="SyntaxError: Unexpected token '<'
Below is what's in the gatsby-ssr.js. It run successfully after run npm start. But when check inspect there is the syntaxError. Please can you check what is causing this error and help me fix it.
gatsby-ssr.js page
import * as React from 'react'
import { Partytown } from '@builder.io/partytown/react'
export function onRenderBody({ setHeadComponents, setPreBodyComponents, setHtmlAttributes }) {
setHtmlAttributes({ lang: 'en' })
setHeadComponents([
<Partytown key="partytown" debug={true} forward={['dataLayer.push']} />,
<script
type="text/partytown"
dangerouslySetInnerHTML={{
__html: ` <script>
function initFreshChat() {
window.fcWidget.init({
token: "3456d-e81e-4201-b9ac-324efdvsffda,
host: "https://wchat.eu.freshchat.com"
});
}
function initialize(i,t){var e;i.getElementById(t)?initFreshChat():((e=i.createElement("script")).id=t,e.async=!0,e.src="https://wchat.freshchat.com/js/widget.js",e.onload=initFreshChat,i.head.appendChild(e))}function initiateCall(){initialize(document,"freshchat-js-sdk")}window.addEventListener?window.addEventListener("load",initiateCall,!1):window.attachEvent("load",initiateCall,!1);
</script>`
}}
/>,
])
// Below is Optional for Disabled JS
setPreBodyComponents([
])
}
CodePudding user response:
The problem is that your script is not valid. As it is, you are adding a <script>
inside a <script>
. Your snippet should look like:
import * as React from "react";
import { Partytown } from "@builder.io/partytown/react";
export function onRenderBody({
setHeadComponents,
setPreBodyComponents,
setHtmlAttributes,
}) {
setHtmlAttributes({ lang: "en" });
setHeadComponents([
<Partytown key="partytown" debug={true} forward={["dataLayer.push"]} />,
<script
type="text/partytown"
dangerouslySetInnerHTML={{
__html: `function initFreshChat() {
window.fcWidget.init({
token: "3456d-e81e-4201-b9ac-324efdvsffda,
host: "https://wchat.eu.freshchat.com"
});
}
function initialize(i,t){var e;i.getElementById(t)?initFreshChat():((e=i.createElement("script")).id=t,e.async=!0,e.src="https://wchat.freshchat.com/js/widget.js",e.onload=initFreshChat,i.head.appendChild(e))}function initiateCall(){initialize(document,"freshchat-js-sdk")}window.addEventListener?window.addEventListener("load",initiateCall,!1):window.attachEvent("load",initiateCall,!1);
`,
}}
/>,
,
]);
// Below is Optional for Disabled JS
setPreBodyComponents([]);
}
Directly adding the script between backticks (`
) should do the trick.
CodePudding user response:
SyntaxError: Unexpected token '<' error message is usually caused when trying to parse a JSON object that's not JSON.stringified, or not parsing it when it is stringified.
if you post the actual stack trace I can help you debug it