Code Monkey home page Code Monkey logo

tawk-messenger-react's People

Contributors

jafin avatar jaoaustero avatar tsivanesar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

tawk-messenger-react's Issues

Translation load issue

I have two widgetsId. One is for English and the other is for Spanish.
So when I switch language from English to Spanish I have to reload twice and then the Spanish widget loads. But when I switch from Spanish to English It takes only one reload to load the English widget in the browser.

here is the code.

const TawkComponent: React.FC<ITawkComponent> = ({ authUser, lang }) => {
  const tawkMessengerRef = useRef<any>();
  const hash = CryptoJS.HmacSHA256('hello XYZ', '1g****3ld');
  const hashInBase64 = CryptoJS.enc.Base64.stringify(hash);

  const onChatMaximized = useCallback(() => {
    tawkMessengerRef.current.setAttributes(
      {
        userId: localStorage.getItem('userId'),
      },
      function (error: any) {
        console.log(error);
      }
    );

    tawkMessengerRef.current.setAttributes(
      {
        name: localStorage.getItem('userName'),
      },
      function (error: any) {
        console.log(error);
      }
    );

    tawkMessengerRef.current.setAttributes(
      {
        email: localStorage.getItem('userEmail'),
      },
      function (error: any) {
        console.log(error);
      }
    );

    tawkMessengerRef.current.setAttributes(
      {
        hash: hashInBase64,
      },
      function (error: any) {
        console.log(error);
      }
    );
  }, []);

  useEffect(() => {
    // Dynamically create and append the Tawk script
    const script = document.createElement('script');
    script.async = true;
    script.charset = 'UTF-8';
    script.setAttribute('crossorigin', '*');

    const widgetId = lang === 'en' || lang === 'de' ? '1g*****ld' : '1g****ccu';
    script.src = `https://embed.tawk.to/633605c554****12d8979f6c/${widgetId}`;

    script.onload = () => {
      window.Tawk_API = window.Tawk_API || {};
      window.Tawk_API.onLoad = () => {
        // Additional logic on Tawk load if needed
      };
    };

    document.head.appendChild(script);

    // Clean up the script tag when the component unmounts
    return () => {
      document.head.removeChild(script);
    };
  }, [lang]);

  return (
    <>
      {authUser ? (
        <TawkMessengerReact
          propertyId='633605c554****12d8979f6c'
          widgetId='1g****3ld'
          ref={tawkMessengerRef}
          onChatMaximized={onChatMaximized}
        />
      ) : (
        <TawkMessengerReact
          propertyId='633605c554****12d8979f6c'
          widgetId='1g****3ld'
          ref={tawkMessengerRef}
        />
      )}
    </>
  );
};

Why does it take two times to reload to the Spanish widget ? How can I fix this?

Changes made through setAttributes are only reflected sporadically in tawkto dashboard

In my code, I use the SecureMode, and I have made sure that the method setAttributes is only called when all values are available. I see in the WebSocket connection that the data is being transmitted successfully. However, the callback function of setAttributes returns undefined, and none of the possible errors mentioned in the documentation. Sometimes, the attributes get updated in the dashboard, but sometimes they don't. Could it be that they are not being added live, or are there currently any issues?

import React, {useEffect, useRef, useState} from 'react';
import {useAuth} from "./auth/context";
import TawkMessengerReact from '@tawk.to/tawk-messenger-react';

function generateName() {...}

const TawkMessenger = () => {
    const tawkMessengerRef = useRef();
    const {user} = useAuth()
    const [isTawkLoaded, setIsTawkLoaded] = useState(false)

    useEffect(() => {
        if (tawkMessengerRef.current == null || user == null || !isTawkLoaded) return
        tawkMessengerRef.current.setAttributes({
            reference: user.id,
            name: generateName(user.firstName, user.lastName),
            email: user.email,
            hash: user.tawktoHash,
        }, function (error: unknown) {
            console.log(error)
        })
    }, [user?.tawktoHash, user?.firstName, user?.lastName, user?.email, user?.id, isTawkLoaded])

    return <TawkMessengerReact
        onLoad={() => { setIsTawkLoaded(true) }}
        propertyId="XXXXX"
        widgetId="XXXXX"
        ref={tawkMessengerRef}
    />
}

export default TawkMessenger

Websocket:
image

Dashboard View:

tawkto

react-scripts dependancies

Hello,

Installing this library in my React App gives me high severity vulnerability warnings:

% npm audit --production

npm audit report

nth-check <2.0.1
Severity: high
Inefficient Regular Expression Complexity in nth-check - GHSA-rp65-9cf3-cjxr
No fix available
node_modules/svgo/node_modules/nth-check
├── css-select <=3.1.0
├── Depends on vulnerable versions of nth-check
└── node_modules/svgo/node_modules/css-select
├── svgo 1.0.0 - 1.3.2
├── Depends on vulnerable versions of css-select
└── node_modules/svgo
├── @svgr/plugin-svgo <=5.5.0
├── Depends on vulnerable versions of svgo
└── node_modules/@svgr/plugin-svgo
├── @svgr/webpack 4.0.0 - 5.5.0
├── Depends on vulnerable versions of @svgr/plugin-svgo
└── node_modules/@svgr/webpack
├── react-scripts >=2.1.4
├── Depends on vulnerable versions of @svgr/webpack
└── node_modules/react-scripts
├── @tawk.to/tawk-messenger-react *
├── Depends on vulnerable versions of react-scripts
└── node_modules/@tawk.to/tawk-messenger-react

7 high severity vulnerabilities

My application is running on react-scripts 5.0.1 and this error does not happen when I uninstall Tawk.to

How to add custom style to the react widget?

I'm trying to put the widget in a custom position. I found the following attribute for javascript api Tawk_API.customStyle
Is it available ussing the react widget? I couldn't find documentation about it

Thanks.

SyntaxError: Cannot use import statement outside a module

Hello,

After installing the official tawk react package, I get this error SyntaxError: Cannot use import statement outside a module. please could you assist in resolving it?

File name where error occurs
file:///C:/Users/user/project/nextjs-project/node_modules/%20(tawk.to/tawk-messenger-react/src/index.js

  • OS - windows
  • Framework - Next.js

Cannot read properties of undefined (reading '$socket')

I tried 2 approaches below but still encountered the same issue. May I know how to resolve this issue?

  1. use @tawk.to/tawk-messenger-react,
    const onLoad = () => {
    console.log('Here', tawkMessengerRef);
    tawkMessengerRef.current.setAttributes({
    name: 'test',
    email: '[email protected]',
    });
    };
image
  1. useeffect to check if authenticated
    useEffect(() => {
    if (isLoggedIn && store.user) {
    // const hash = hashInBase64(store.user.email, window.TAWK_APIKEY);
    if (window.Tawk_API) {
    window.Tawk_API.setAttributes(
    {
    name: store.user.loginName ?? '',
    email: store.user.email ?? '',
    // hash: hash,
    },
    function (error) {
    if (error) {
    console.error('Tawk update user information error:', error);
    }
    },
    );
    }
    }
    }, [store.user]);

Bug on onChatStarted and localstorage

`import axios from 'axios';
import { useEffect, useRef } from 'react';

const TawkMessengerReact = require('@tawk.to/tawk-messenger-react');

const ChatSupport = () => {

const onPrechatSubmit = async (data: IPreChatDetails[]) => {
try {
const response = await axios.post('/api/sample', data);
const name = response.data.user[0].answer;
const email = response.data.user[1].answer;
localStorage.removeItem('name');
localStorage.removeItem('email');
localStorage.setItem('name', name);
localStorage.setItem('email', email);
console.log('pre submit submitted!');
} catch (err) {
console.error(err);
}
};

const onChatStarted = async () => {
try {
const name = localStorage.getItem('name');
const email = localStorage.getItem('email');
console.log(name);
const response = await axios.post('/api/sample', {
name,
email,
});
console.log('started');
} catch (err) {
console.log(err);
}
};

return (

);
};

export default ChatSupport;
`

When running it on the browser and triggering the onPrechatSubmit and onChatStarted, this is the order on the browser's console:
null --> console.log(name);
pre-chat submitted! --> console.log('pre submit submitted!');
started --> console.log('started');

How Do I manually Open The Widget

Hi there, I'm trying to open the widget when ever the user clicks a separate button on my app and i have gone through the https://github.com/tawk/tawk-messenger-vue-2/blob/424139a03b772dbd0e3463b9d551fcf49af7ffb6/docs/api-reference.md but i can't find anything to solve my problem.

The only similar callback function i saw was the maximize(); function but that makes the widget take up the whole view port screen and that's not what i want. i just want to mimic the feature where the user clicks on the widget.

Out of date

tried to install and got this error


% npm install @tawk.to/tawk-messenger-react
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/typescript
npm ERR!   peerOptional typescript@">=3.3.1" from [email protected]
npm ERR!   node_modules/eslint-config-next
npm ERR!     eslint-config-next@"13.2.4" from the root project
npm ERR!   peer typescript@">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" from [email protected]
npm ERR!   node_modules/tsutils
npm ERR!     tsutils@"^3.21.0" from @typescript-eslint/[email protected]
npm ERR!     node_modules/@typescript-eslint/typescript-estree
npm ERR!       @typescript-eslint/typescript-estree@"5.57.1" from @typescript-eslint/[email protected]
npm ERR!       node_modules/@typescript-eslint/parser
npm ERR!         @typescript-eslint/parser@"^5.42.0" from [email protected]
npm ERR!         node_modules/eslint-config-next
npm ERR!         1 more (eslint-config-react-app)
npm ERR!   1 more (the root project)
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peerOptional typescript@"^3.2.1 || ^4" from [email protected]
npm ERR! node_modules/react-scripts
npm ERR!   peer react-scripts@"^5.0.1" from @tawk.to/[email protected]
npm ERR!   node_modules/@tawk.to/tawk-messenger-react
npm ERR!     @tawk.to/tawk-messenger-react@"*" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/typescript
npm ERR!   peerOptional typescript@"^3.2.1 || ^4" from [email protected]
npm ERR!   node_modules/react-scripts
npm ERR!     peer react-scripts@"^5.0.1" from @tawk.to/[email protected]
npm ERR!     node_modules/@tawk.to/tawk-messenger-react
npm ERR!       @tawk.to/tawk-messenger-react@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! 
npm ERR! For a full report see:
npm ERR! /Users/russellharrower/.npm/_logs/2023-04-30T07_21_53_013Z-eresolve-report.txt

Deque Axe Tests failing

Hey, I've added the React component to a project and it has a couple of accessibility tests failing.

Steps to reproduce:

  • Add Tawk React component to a project
  • Run axe Devtools extension or run e2e accessibility tests e.g. @axe-core/playwright

Errors:

Please get in touch if more detail is required.

The chat widget sometimes appear during dev localhost:3000 but doesn't appear at all when deployed to vercel

Below is my _app.tsx file. Is there anything I missed out hence the chat widget doesn't appear? or is it because it's not supported once deployed to vercel because i understand vercel does not support subscription?

Thanks

_app.tsx

const TawkMessengerReact = dynamic(
  () =>
    // @ts-ignore
    import("node_modules/@tawk.to/tawk-messenger-react")
);

function MyApp({ Component, pageProps: { ...pageProps } }: AppProps) {
  const router = useRouter();

  const initialRenderRef = useRef(false);
  const tawkMessengerRef = useRef();

 useEffect(() => {
    initialRenderRef.current = true;
  }, []);

return (
        {initialRenderRef.current && (
          <TawkMessengerReact
            // @ts-ignore
            propertyId={process.env.NEXT_PUBLIC_TAWK_PROPERTY_ID}
            widgetId={process.env.NEXT_PUBLIC_WIDGET_ID}
            useRef={tawkMessengerRef}
          />
        )}
        <Component {...pageProps} />
)

Minor documentation error

Thank you for this component, works just fine.

Here in the doc: https://help.tawk.to/article/react-js :: How to use callbacks and expose functions

This

        <TawkMessengerReact
          propertyId="property_id"
          widgetId="default"
          useRef={tawkMessengerRef}
        />

should be

        <TawkMessengerReact
          propertyId="property_id"
          widgetId="default"
          ref={tawkMessengerRef}
        />

The prop should be ref not useRef.

Weird behaviour of the widget

Weird behaviour of the widget. It "auto opens" (but not even as it should) on page visit, always only on the first load. I am observing this weird behaviour on my development website but also on https://help.tawk.to/article/react-js with your own widget. Please note the cursor is hidden on the screen recording.

Screencast.from.2024-06-25.12-19-39.webm

Confusing documentation, setAttributes not working

When using setAttributes(), the attributes are not set and the error UNAUTHORIZED_API_CALL is passed to the callback function. It could be caused by a wrong hash, but I am not sure.
Issue 1: That error code is nowhere to be found in the docs, so I have no idea what it means.

Issue 2: The documentation has conflicting information about calculating the hash:
"hash is a combination of userId + site API key using HMAC SHA256" and "The hash is server side generated HMAC using SHA256, the user’s email and your site’s API key."

Issue 3: The how-to-use.md is stilling using useRef={} instead of ref={} (another issue mentioned this)

Could someone please give me input on my React code and maybe point me in the right direction? I would really appreciate that.

import React, { useRef } from 'react'
import TawkMessengerReact from '@tawk.to/tawk-messenger-react'
import * as CryptoJS from 'crypto-js'
import { TAWK_API_KEY } from './constants/constants'

interface TawkMessengerReactRef {
  setAttributes: (attributes: object, callback: (error: any) => void) => void
}

export default function Container() {
  const tawkMessengerRef = useRef<TawkMessengerReactRef | null>(null)

  const onLoad = () => {
    if (tawkMessengerRef?.current?.setAttributes) {
      const {
        myshopifyDomain,
        contactEmail,
        appBlocksSupported,
        installedOn,
        planName,
      } = merchantInformation
      const hash = hashInBase64(myshopifyDomain)
      tawkMessengerRef.current.setAttributes(
        {
          hash,
          userId: myshopifyDomain,
          name: myshopifyDomain,
          email: contactEmail,
          appBlocksSupported,
          installedOn,
          planName,
        },
        function (e) {
          console.log(e)
        },
      )
    }
  }

  function hashInBase64(userId) {
    var hash = CryptoJS.HmacSHA256(userId, TAWK_API_KEY)
    return CryptoJS.enc.Hex.stringify(hash)
  }

  return <AppContext.Provider value={} >
            <Routes pages={pages} />
            <TawkMessengerReact
              propertyId="6503..."
              widgetId="1haa..."
              onLoad={onLoad}
              ref={tawkMessengerRef}
            />
          </AppContext.Provider>
}

The hash comes out like this: 32422195d1615c8c23d46ff496e23b032aa71df7b6b85d97a8f832121991dfbc
Secure Mode is enabled.
Secret is stored on the frontend only for development purposes.
I am not even able to find the request going out, so I have no idea how to continue debugging this.

Thank you! :)

Access From my Origin is Being Blocked By Cors Policy

Hi there, i started getting this cors error in my broswer recently and i don't know what i did wrong, everything worked fine the first time i implemented tawk on my website.

Please note that the chat widget still works when a user sends a complaint, also this error only pops up on the app initial render routing between pages doesn't display subsequent errors.

Please how can i clear this Cors error ?
tawkError

The result of callback doesnt have any message, tawkto has change the result ?

I need your helps, my app have been using TawkMessengerReact for work since 2 month, but currently it doesn't work.
When my customers chat on widget chat, the app not return any data. Althought, dashboard tawkto still get the message, but my app just get the status "ok" and data messages empty (only "co" and "cver", but it not helpful to me). I think that tawk.to did something to block message and make data empty messages. My app use method onChatMessageVisitor

PURPOSE: I need the data message from data reusult and send to my bot telegram

<TawkMessengerReact
      propertyId={propertyId}
      customStyle={customstyle}
      widgetId={widgetId}
      ref={tawkMessengerRef}
      onChatMessageVisitor={(mess: string) => {
      console.log("mess: ", mess)
        setMsg(mess)
      }}
/>

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.