-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathcontent.js
64 lines (56 loc) · 2.08 KB
/
content.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
62
63
64
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action === 'getProductImage') {
getProductImageUrl(request.openAIApiKey).then(sendResponse);
return true; // Indicates we will send a response asynchronously
}
});
async function getProductImageUrl(openAIApiKey) {
const htmlContent = document.documentElement.outerHTML;
const productImageUrl = await getProductImageFromGPT(
htmlContent,
openAIApiKey
);
return { productImageUrl };
}
async function getProductImageFromGPT(htmlContent, openAIApiKey) {
console.log('getProductImageFromGPT', openAIApiKey, !openAIApiKey);
if (!openAIApiKey) {
console.error('OpenAI API key not provided');
return null;
}
const apiUrl = 'https://api.openai.com/v1/chat/completions';
const prompt = `
Analyze the following HTML content and extract the URL of the main product image.
Look for both <img> tags and CSS background-image properties.
Consider elements and children with class names or IDs containing words like 'product-image' 'product', 'main', 'featured' etc.
Return only the full URL with commonly used image extensions (jpg, jpeg, png, webp) of the main product image in JSON format, with the key "productImageUrl".
If you can't find a product image, return {"productImageUrl": null}.
HTML content:
${htmlContent.substring(
0,
50000
)} // Limiting to few characters to avoid exceeding token limits
`;
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${openAIApiKey}`,
},
body: JSON.stringify({
model: 'gpt-4o',
messages: [{ role: 'user', content: prompt }],
response_format: {
type: 'json_object',
},
}),
});
const data = await response.json();
const result = JSON.parse(data.choices[0].message.content.trim());
return result.productImageUrl;
} catch (error) {
console.error('Error fetching product image from GPT-4o:', error);
return null;
}
}