Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
95 lines (83 loc) · 3.5 KB
/
Copy pathbackground.js
File metadata and controls
95 lines (83 loc) · 3.5 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// 1. インストール時の初期設定
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "describe-image",
title: "Geminiで画像を説明する",
contexts: ["image"]
});
});
// 2. メニュークリック時の処理
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId === "describe-image") {
// ステップA: とりあえずウィンドウを開く (ユーザーへの即時フィードバック)
// 以前の結果が残らないようにストレージを「読込中」で初期化
await chrome.storage.local.set({
analysisResult: { status: 'loading' }
});
// ダイアログウィンドウを作成 (ポップアップタイプ)
chrome.windows.create({
url: "result.html",
type: "popup",
width: 400,
height: 500,
focused: true
});
// ステップB: 解析処理の実行
try {
// APIキー取得
const { geminiApiKey } = await chrome.storage.local.get("geminiApiKey");
if (!geminiApiKey) throw new Error("APIキーが設定されていません。オプションから設定してください。");
// 画像取得 & APIコール
const base64Image = await fetchImageAsBase64(info.srcUrl);
const description = await callGeminiApi(geminiApiKey, base64Image);
// ステップC: 結果をストレージに保存 (ウィンドウ側がこれを検知して表示更新)
await chrome.storage.local.set({
analysisResult: { status: 'success', text: description }
});
} catch (error) {
console.error(error);
// エラー情報を保存
await chrome.storage.local.set({
analysisResult: { status: 'error', error: error.message }
});
}
}
});
// --- 補助関数 (変更なし) ---
async function fetchImageAsBase64(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`画像の取得失敗: ${response.status}`);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (e) {
throw new Error("画像のダウンロードに失敗しました。アクセス権限などの問題の可能性があります。");
}
}
async function callGeminiApi(apiKey, base64Image) {
const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`;
const payload = {
contents: [{
parts: [
{ text: "この画像を日本語で詳しく、わかりやすく説明してください。" },
{ inline_data: { mime_type: "image/jpeg", data: base64Image } }
]
}]
};
const response = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error?.message || "APIエラー");
}
const data = await response.json();
return data.candidates[0].content.parts[0].text;
}