function messageHandler()

in src/contentScripts/index.ts [51:96]


function messageHandler() {
  onMessage<TranslateCommandData, 'translate'>(
    'translate',
    ({ sender: { context, tabId }, data }) => {
      // Destructure our configuration
      const { creds, langs } = data;
      const { source, target } = langs;

      // Send a message informing the popup that the translation has started
      void sendMessage('status', { status: 'translating', message: '' }, 'popup');

      // Start the webpage translation process
      const startingEl = document.querySelector('body');

      startTranslation(creds, source, target, startingEl)
        .then(() => {
          // Send a message to the popup indicating the translation has completed
          void sendMessage(
            'status',
            { status: 'complete', message: 'Translation complete.' },
            'popup'
          );
        })
        .catch(e => {
          console.error(e, startingEl);

          // Send a message to the popup indicating that an error occurred during translation
          void sendMessage(
            'status',
            { status: 'error', message: 'An error occurred. The document failed to translate.' },
            { context, tabId }
          );
        });
    }
  );

  // Listen to requests to clear the current page's translation cache
  onMessage('clearCache', ({ sender: { context, tabId } }) => {
    lockr.rm(window.location.href);
    void sendMessage(
      'status',
      { status: 'complete', message: 'Cleared cache for this page.' },
      { context, tabId }
    );
  });
}