Search code examples
reactjsmicrosoft-teamsmicrosoft-teams-jsmsteams-react-base-component

MS Teams Personal App - Detect User Leaving the Personal App


I have created a MS Teams personal app using react and fluent UI react northstar library.

There is a requirement from the client to generate a KPI for each user's time spent inside the app.

I can get the user in time for the app, but the question is

How can I detect the user has leave the app by clicking outside the app?

For Example, user is in my personal app and then he clicks on chat, calls, calendar etc. then I need to detect that, he has left the personal app.

Any help is appreciated in this case.

Thanks


Solution

  • To detect when a user leaves your MS Teams personal app, you can use the onBlur event to detect when the app loses focus. You can add an event listener to the window object that listens for the blur event and calls a function to record the time spent by the user in your app.

    Here's an example code snippet:

    import { useEffect } from 'react';
    
    function App() {
      useEffect(() => {
        window.addEventListener('blur', handleAppBlur);
    
        return () => {
          window.removeEventListener('blur', handleAppBlur);
        };
      }, []);
    
      function handleAppBlur() {
        // Record the time spent by the user in your app
        // when the app loses focus
      }
    
      return (
        // Your app code
      );
    }
    
    export default App;
    

    This code adds an event listener for the blur event when the component mounts and removes it when the component unmounts. The handleAppBlur function is called when the app loses focus, and you can record the time spent by the user in your app in this function.

    Note that this approach will detect when the user clicks outside your app in the same browser window or tab, but it won't detect if the user switches to a different browser window or tab.

    You can find about JS blur event here.