/
background.js
61 lines (59 loc) · 2.37 KB
/
background.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === "fetchText") {
// Use chrome.tabs.query to get the active tab in the current window
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
// tabs[0] will be the active tab in the current window
const currentTab = tabs[0];
chrome.scripting.executeScript({
target: { tabId: currentTab.id },
function: getTextFromPage
}, (injectionResults) => {
for (const frameResult of injectionResults)
sendTextToApi(frameResult.result, sendResponse);
});
});
return true; // Will respond asynchronously.
}
});
function getTextFromPage() {
return document.body.innerText;
}
function sendTextToApi(text, sendResponse) {
fetch('http:https://localhost:11434/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(
{
model: "phi3",
prompt: text,
system: "Given text from a webpage, generate a brief summary. Answer in only plaintext format.",
stream: false,
}
)
})
.then(response => {
// Log the text response for debugging purposes
response.text().then(text => {
console.log("Received text:", text);
try {
// Attempt to parse it as JSON
const data = JSON.parse(text);
if (data && data.response) {
sendResponse(data.response.replace(/\n/g, "\n")); // Send only the "response" key with newline replaced by <br>
} else {
sendResponse("No response found."); // Fallback text
}
} catch (e) {
// Log parsing errors
// console.error("Error parsing JSON:", e);
console.error("Error parsing JSON:", text);
sendResponse("Error in parsing response.");
}
});
})
.catch(error => {
console.error('Error:', error);
sendResponse("Error in fetching response. Make sure Ollama is running and serving on host 'localhost' and port '11434'."); // Error handling
});
return true; // To allow asynchronous response
}