This is a chrome Extension project that aims to produce summary and major points of a selected text on the web. I'm new to chrome extension development and trying to run this code. Any suggestion and help will be greatly valued.

**Manifest.json file **

//manifest.json
{
  "manifest_version": 3,
  "name": "Text Summarizer and Major Points generator",
  "version": "1.0",
  "description": "A Chrome extension that uses OpenAI API to summarize or produce major poinnts on the selected text.",
  "permissions": [
    "contextMenus",
    "storage",
    "activeTab",
    "scripting",
    "tabs"
  ],
  "action": {
    "default_popup": "popup.html"
  },
  "icons": {
    "16": "images/icon16.png",
    "48": "images/icon48.png",
    "128": "images/icon128.png"
  },
  "host_permissions": [
    "https://*.openai.com/"
  ],
  "background": {
    "service_worker": "background.js"
  },
 
  "options_page": "options.html"
 
}```
**background.js file**
``chrome.runtime.onInstalled.addListener(function () {
  chrome.contextMenus.create({
    id: 'summarize',
    title: 'Summarize it',
    contexts: ['selection'],
  });

  chrome.contextMenus.create({
    id: 'majorpoints',
    title: 'Major Point it',
    contexts: ['selection'],
  });
});

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

      async function fetchDataAndInteract (info) {

      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 the major point of this post: ${selectedText}`;

        const response = await fetch('https://api.openai.com/v1/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:' : 'Major Points:';

          chrome.scripting.executeScript({
            target: { tabId: tab.id },
            function: showResult,
            args: [resultTitle, resultText],
          });

        } else {
          console.error('No choices returned from API call.');
        }
      });
    }

    async function showResult(resultTitle, resultText) {
      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);
    }

Content.js

//content.js
chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) {
  if (request.action === 'showResult') {
    console.log('Message received in content.js:', request);
    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 });
  } 
  // sendResponse({ success: true });
});

popup.js

// 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 && globalData.action === 'summarize' || globalData.action === 'majorpoints') {
      const apiKey = globalData.apiKey;
      const selectedText = globalData.selectedText;
      const prompt = globalData.action === 'summarize' ? `Summarize: ${selectedText}` : `Major Points of: ${selectedText}`;

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

      try {
        const response = await fetch('https://api.openai.com/v1/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/Major Point:', error);
        result.textContent = 'An error occurred. Please try again later.';
      }
    }
  });
});

Popup.html


<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        width: 300px;
        height: 200px;
        font-family: Arial, sans-serif;
      }
    </style>
  </head>
  <body>
    <h3 id="title"></h3>
    <div id="result"></div>
    <script src="popup.js"></script>
  </body>
</html>

I am new to chrome extension development and trying to run this code. Any suggestion and help will be greatly valued.

The problem is with handling promises. However i'm clueless as of how to correctly handle async/await.

0

There are 0 best solutions below