I am trying to create a google extension with openai api. After researching around for a while I made this code. However, when I type in the question and click “Ask”, these 2 errors appeared on console:
-Error handling response: TypeError: Cannot read properties of undefined (reading ‘answer’) at chrome-extension://enfpcdboapcobchgbmiiklnljabckpof/popup/popup.js:9:32
-Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
I don’t know what is the problem. I am new to javascript so sorry if I made any dump mistake. Here is the code:
manifest.json
{
"manifest_version": 3,
"name": "GPT",
"version": "1.0.0",
"description": "OpenAI",
"background": [{
"matches": ["https://www.google.com/*"],
"service_worker": ["background.js"],
"persistent": true
}],
"action": {
"default_popup": "popup/popup.html"
},
"icons": {
"16": "images/icon-16.png",
"32": "images/icon-32.png",
"128": "images/icon-128.png"
}
}
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TrainerAI</title>
<link rel="stylesheet" href="bulma.min.css">
</head>
<body>
<div class="container m-3">
<h1 class="title">TrainerAI</h1>
</div>
<div class="container m-3">
<div class="field">
<label class="label">Ask Anything</label>
<div class="control">
<input type="text" class="input" id="questionBox">
</div>
</div>
</div>
<div class="container m-3">
<button class="button is-success is-fullwidth" id="askButton"> Ask </button>
</div>
<div class="container m-3">
<div class="field">
<label class="label">Result</label>
<div class="control">
<textarea class="textarea" id="resultBox" rows="10" readonly></textarea>
</div>
</div>
</div>
</body>
<script src="popup.js"></script>
</html>
popup.js
const questionBox = document.getElementById("questionBox");
const askButton = document.getElementById("askButton");
const resultBox = document.getElementById("resultBox");
// Send message to background.js on button click
askButton.addEventListener("click", () => {
chrome.runtime.sendMessage({ question: questionBox.value }, (response) => {
// Display response from background.js in resultBox
resultBox.value = response.answer;
});
});
background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// Check if the message is a question
if (request.question) {
const apiUrl = "https://api.openai.com/v1/completions";
const apiKey = "";
const model = "text-davinci-003";
const prompt = `${request.question}
fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
},
body: JSON.stringify({
"model": model,
"prompt": prompt,
"max_tokens": 300,
"temperature": 0,
}),
})
.then(response => response.json())
.then(data => {
const answer = data.choices[0].text;
console.log(answer)
sendResponse({ answer: answer });
})
.catch(error => console.log(error));
return true;
}
});