Skip to content

Instantly share code, notes, and snippets.

@JohnGoodman
Last active September 8, 2023 06:52
Show Gist options
  • Save JohnGoodman/358207249e4d0722cf18f1ed89a89591 to your computer and use it in GitHub Desktop.
Save JohnGoodman/358207249e4d0722cf18f1ed89a89591 to your computer and use it in GitHub Desktop.
Tawk.to React function to to toggle showing and hiding the widget
// In a react app, the Tawk.to widget loads before the React app, causing an error to be thrown
// if you need to interact with the widget on first load
// The code below checks to make see if the widget it initialized
// It handles toggling the widget even when it has not initalized yet
function tawkWidgetToggle(show){
// Ensure the Tawk object has initalized
if(window.$_Tawk && window.$_Tawk.init){
show ? showWidget() : hideWidget();
}else{
// If the Tawk object didn't initilize, use a differnt method of loading
if( window.Tawk_API ){
window.Tawk_API.onLoad = function(){
show ? showWidget() : hideWidget();
};
}
}
}
function showWidget() {
window.Tawk_API.showWidget();
}
function hideWidget() {
window.Tawk_API.hideWidget();
}
export default tawkWidgetToggle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment