Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamically change tawk locale

If you need to change tawk's locale dynamically (i.e. in SPA), here is the code I use. There is a small issue, though - everytime tawk adds new div to body and there is no way to correctly detect it and remove (ids are dynamic and there is no classname). However, as far as it is hidden, this should not be a problem.

function _setupTawk(locale) {
/**
* Links for language-specific channels or projects, you can find them in original tawk embed code
*/
const localeToLink = {
ru: 'https://embed.tawk.to/secret/secret',
en: 'https://embed.tawk.to/secret/secret',
};
/**
* Hide widget if tawk is loaded
*/
if (
window.Tawk_API !== undefined &&
typeof window.Tawk_API.hideWidget === 'function'
) {
window.Tawk_API.hideWidget();
}
/**
* Delete script tags of tawk
*/
const scripts = document.getElementsByTagName('script');
for (let i = 0; i < scripts.length; i++) {
const tag = scripts[i];
if (tag.getAttribute('tawk') === 'yes') {
tag.parentNode.removeChild(tag);
}
}
/**
* Delete anything related to tawk, otherwise new widget would not be loaded
*/
for (const name in window) {
if (
window.hasOwnProperty(name) &&
(name.includes('tawk') || name.includes('Tawk'))
) {
delete window[name];
}
}
/**
* Almost the same code as original
*/
window.Tawk_API = {};
window.Tawk_LoadStart = new Date();
(function() {
const s1 = document.createElement('script'),
s0 = document.getElementsByTagName('script')[0];
s1.async = true;
s1.src = localeToLink[locale]; //Here we use correct url for locale
s1.charset = 'UTF-8';
s1.setAttribute('crossorigin', '*');
s1.setAttribute('tawk', 'yes'); //This line is used to mark tawk script
s0.parentNode.insertBefore(s1, s0);
})();
}
@betoflakes

This comment has been minimized.

Copy link

@betoflakes betoflakes commented Nov 3, 2020

Have you used this code recently?
I'm facing a sessionHandler or viewHandler error when hideWidget or any Tawk API services.

Cannot read property 'viewHandler' of null at Object.u.hideWidget.Tawk_API.hideWidget

@GendelfLugansk

This comment has been minimized.

Copy link
Owner Author

@GendelfLugansk GendelfLugansk commented Nov 3, 2020

Have you used this code recently?
I'm facing a sessionHandler or viewHandler error when hideWidget or any Tawk API services.

Cannot read property 'viewHandler' of null at Object.u.hideWidget.Tawk_API.hideWidget

Yes, I have a web app that contains this code and it works just fine for me. You can try to visit https://app.tradary.com/ from PC (tawk there is disabled on mobile), switch language and see if it changes tawk widget.

@HenriqueSath

This comment has been minimized.

Copy link

@HenriqueSath HenriqueSath commented Feb 3, 2021

I'm getting the error TypeError: Cannot delete property 'Tawk_API' of #<Window>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment