Friday, April 5, 2024

Create a Chrome extension using Manifest V3 to make API calls to OpenAI

 1.    Create a Manifest File (manifest.json)

{
  "manifest_version": 3,
  "name": "OpenAI Chrome Extension",
  "version": "1.0",
  "permissions": ["https://api.openai.com/*"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icon.png",
      "48": "icon.png",
      "128": "icon.png"
    }
  },
  "background": {
    "service_worker": "background.js"
  }
}


2.    Create a Popup HTML File (popup.html)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>OpenAI Extension Popup</title>
  <script src="popup.js"></script>
</head>
<body>
  <div id="response"></div>
</body>
</html>

3.   Create a Popup JavaScript File (`popup.js`)

async function fetchData() {
  try {
    const response = await fetch('https://api.openai.com/v1/your_endpoint', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        // Your request body data
      })
    });
    const data = await response.json();
    document.getElementById('response').textContent = JSON.stringify(data, null, 2);
  } catch (error) {
    console.error('Error fetching data:', error);
    document.getElementById('response').textContent = 'Error fetching data';
  }
}

document.addEventListener('DOMContentLoaded', fetchData);

4.   Create a Background JavaScript File (background.js)

// This file is empty for now, but can be used for background tasks if needed

5. Replace `"your_endpoint"` with the appropriate endpoint from OpenAI's API and `"YOUR_API_KEY"` with your actual OpenAI API key.

6. Load the Extension in Chrome
   - Open Chrome and go to `chrome://extensions/`.
   - Enable Developer mode.
   - Click on "Load unpacked" and select the directory containing your extension files.

This is a basic setup to get you started. Make sure to handle errors, API key securely, and consider adding more features as needed.




No comments: