Skip to content

Instantly share code, notes, and snippets.

@mwdchang
Created May 24, 2025 17:45
Show Gist options
  • Save mwdchang/288386974ab5121f7d848b281b84f37e to your computer and use it in GitHub Desktop.
Save mwdchang/288386974ab5121f7d848b281b84f37e to your computer and use it in GitHub Desktop.
ChatGPT Chrome plugin starter

manifest

{
  "manifest_version": 3,
  "name": "OpenAI Assistant",
  "version": "1.0",
  "description": "A Chrome extension that uses OpenAI's API.",
  "permissions": ["storage", "activeTab", "scripting"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icon16.png",
      "48": "icon48.png",
      "128": "icon128.png"
    }
  },
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": ["<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html>
<head>
  <title>OpenAI Assistant</title>
  <script src="popup.js" defer></script>
</head>
<body>
  <textarea id="input" placeholder="Type your prompt here..." rows="5" cols="30"></textarea>
  <button id="send">Send</button>
  <pre id="response"></pre>
</body>
</html>

popup.js

document.getElementById("send").addEventListener("click", async () => {
  const prompt = document.getElementById("input").value;
  const responseField = document.getElementById("response");

  const apiKey = "YOUR_OPENAI_API_KEY";  // Store this more securely in production

  const response = await fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      model: "gpt-4",
      messages: [{ role: "user", content: prompt }],
      max_tokens: 150
    })
  });

  const data = await response.json();
  responseField.textContent = data.choices?.[0]?.message?.content || "No response";
});

server

npm install express cors axios dotenv

require('dotenv').config();
const express = require('express');
const axios = require('axios');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());

app.post('/api/chat', async (req, res) => {
  const { prompt } = req.body;

  try {
    const response = await axios.post('https://api.openai.com/v1/chat/completions', {
      model: "gpt-4",
      messages: [{ role: "user", content: prompt }],
      max_tokens: 150
    }, {
      headers: {
        'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });

    res.json(response.data);
  } catch (err) {
    console.error(err.response?.data || err.message);
    res.status(500).json({ error: 'Error contacting OpenAI' });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment