0

I'm developing a Chrome extension that involves injecting content scripts, but I'm encountering an error that I can't resolve. The error message I'm getting is "Uncaught TypeError: Cannot read properties of undefined (reading 'action')". This error gets triggered when i open the popup. The console highlights this part:
if (globalData.action === 'summarize' || globalData.action === 'comment') Below i have pasted 3 files, popup.js, content.js, and background.js. manifest_version: 3.

//popup.js

document.addEventListener('DOMContentLoaded', async function () {
  chrome.runtime.sendMessage({ action: 'processText' }, async function (globalData) {
    const title = document.getElementById('title');
    const result = document.getElementById('result');

    if (globalData.action === 'summarize' || globalData.action === 'comment') {
      const apiKey = globalData.apiKey;
      const selectedText = globalData.selectedText;
      const prompt = globalData.action === 'summarize' ? `Summarize: ${selectedText}` : `Comment on: ${selectedText}`;

      title.textContent = globalData.action === 'summarize' ? 'Summary:' : 'Comment:';
      result.textContent = 'Loading...';

      try {
        const response = await fetch('https://api.openai.com/v1/engines/davinci-codex/completions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`,
          },
          body: JSON.stringify({
            prompt: prompt,
            max_tokens: 50,
            n: 1,
            stop: null,
            temperature: 0.7,
          }),
        });

        const data = await response.json();
        const resultText = data.choices[0].text.trim();
        result.textContent = resultText;
      } catch (error) {
        console.error('Error fetching the summary/comment:', error);
        result.textContent = 'An error occurred. Please try again later.';
      }
    }
  });
});
// background.js

chrome.runtime.onInstalled.addListener(function () {
  chrome.contextMenus.create({
    id: 'summarize',
    title: 'Summarize it',
    contexts: ['selection'],
  });

  chrome.contextMenus.create({
    id: 'comment',
    title: 'Comment it',
    contexts: ['selection'],
  });
});

chrome.contextMenus.onClicked.addListener(async function (info, tab) {
  if (info.menuItemId === 'summarize' || info.menuItemId === 'comment') {
    // Inject the content script
    chrome.scripting.executeScript( { 
      target:{tabId: tab.id},
      files: ['content.js'] }
      );
    }
  });

// content.js

async function fetchDataAndInteract(){

      // Check for any errors during content script injection
      if (chrome.runtime.lastError) {
        console.error(chrome.runtime.lastError.message);
        return;
      }

      chrome.storage.sync.get('openaiApiKey', async function (apiKeyData) {
        const apiKey = apiKeyData.openaiApiKey;

        if (!apiKey) {
          alert('Please set your OpenAI API key in the extension settings.');
          return;
        }

        const action = info.menuItemId;
        const selectedText = info.selectionText;
        const prompt = action === 'summarize' ? `Summarize: ${selectedText}` : `Write a comment reply for this post: ${selectedText}`;

        const response = await fetch('https://api.openai.com/v1/engines/text-davinci-003/completions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`,
          },
          body: JSON.stringify({
            prompt: prompt,
            max_tokens: 100,
            n: 1,
            stop: null,
            temperature: 0.3,
          }),
        });

        const resultData = await response.json();

        if (resultData.choices && resultData.choices.length > 0) {
          const resultText = resultData.choices[0].text.trim();
          const resultTitle = action === 'summarize' ? 'Summary:' : 'Comment:';

          chrome.tabs.sendMessage(tab.id, {
            action: 'showResult',
            resultTitle: resultTitle,
            resultText: resultText,
          }, function(response) {
            console.log('Message sent to content.js:', response);
          });
        } else {
          console.error('No choices returned from API call.');
        }
      });
  const { resultTitle, resultText } = request;
     
  const popup = document.createElement('div');
  popup.style.position = 'fixed';
  popup.style.top = '20%';
  popup.style.left = '50%';
  popup.style.transform = 'translate(-50%, -50%)';
  popup.style.zIndex = '9999';
  popup.style.backgroundColor = 'rgba(255, 255, 255, 0.9)';
  popup.style.padding = '20px';
  popup.style.borderRadius = '10px';
  popup.style.maxWidth = '80%';
  popup.style.textAlign = 'center';
  popup.style.fontFamily = 'Arial, sans-serif';

  const title = document.createElement('h3');
  title.innerText = resultTitle;
  title.style.marginBottom = '10px';
  popup.appendChild(title);

  const result = document.createElement('p');
  result.innerText = resultText;
  popup.appendChild(result);

  document.body.appendChild(popup);

  setTimeout(function () {
    document.body.removeChild(popup);
  }, 10000);

  // sendResponse({ success: true });
}


chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
  if (request.action === 'showResult') {
    console.log('Message received in content.js:', request);
    // const { resultTitle, resultText } = request;

    await fetchDataAndInteract();
    sendResponse({ success: true });
  }
  sendResponse({ success: true });
}
);

I tried to update the highlighted part to this one and it didn't help. if (globalData && globalData.action === 'summarize' || globalData.action === 'comment')

I expect to get the summary of a selected text. Please let me know if other files are required to know more about the error.

Reenu
  • 1
  • 2
  • 1
    I find it highly unlikely you're using Chrome version 3, considering the most recent version is 116, and I don't believe Chrome v3 support `async` functions (or `fetch`, or a number of other things). – Heretic Monkey Aug 28 '23 at 19:04
  • Sorry, i meant manifest_version as 3. I am new to this so I got a bit confused. Thank you for the insight though. Actually, I have been trying to update someone's code which was manifest_version 2. I have updated the basic structure but now I think I have ruined the flow of it. I will highly appreciate any suggestions. and your advise will be of great value to me. – Reenu Aug 28 '23 at 20:00
  • There are several problems. 1) Don't use `async` listener in onMessage, [more info](/a/53024910). 2) Don't use chrome.tabs in content script, it's unavailable. 3) Use chrome.tabs.sendMessage in the popup. 4) Load content.js only via chrome.scripting or content_scripts and remove it elsewhere e.g. from popup.html. – wOxxOm Aug 29 '23 at 03:41

0 Answers0