Hello,
We use zendesk chat in our application using React.js. With the help of a hook like the one below, we add the widget on other pages that we use other than the login page. However, when I look at the developer console, I see that 2 widgets have been added. How can we fix this?
Normally 2 scripts were added but we are cleaning this.
const useZendeskScript = (user) => {
useEffect(() => {
if (user && Object.keys(user).length > 0) {
const existingScript1 = document.getElementById('ze-snippet');
if (existingScript1) {
document.body.removeChild(existingScript1);
}
const script1 = document.createElement('script');
script1.src = `https://static.zdassets.com/ekr/snippet.js?key=${
systemConfig.zendesk.zendeskSourceKey
}`;
script1.id = 'ze-snippet';
script1.async = true;
script1.onload = async () => {
const token = await generateToken(user);
const existingScript2 = document.getElementById('ze-settings-script');
if (existingScript2) {
document.body.removeChild(existingScript2);
}
const script2 = document.createElement('script');
script2.id = 'ze-settings-script';
script2.textContent = `
zE("messenger", "loginUser",
function jwtCallback(callback) {
callback("${token}")
},
function loginCallback(error) {
if (error) {
const { type, reason, message } = error
console.log("Zendesk Login User Error => ", message);
}
}
);
zE("messenger:set", "conversationTags", ["colarx", "web_widget"]);
`;
document.body.appendChild(script2);
};
document.body.appendChild(script1);
return () => {
if (document.body.contains(script1)) {
document.body.removeChild(script1);
}
const script2Element = document.getElementById('ze-settings-script');
if (script2Element && document.body.contains(script2Element)) {
document.body.removeChild(script2Element);
}
};
}
return () => {};
}, [user]);
};