Repository navigation
Expand file tree
/
Copy pathgif_viewer.js
More file actions
92 lines (73 loc) · 2.26 KB
/
Copy pathgif_viewer.js
File metadata and controls
92 lines (73 loc) · 2.26 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
const GIF_STORAGE_KEY = "exportedGifData";
const GIF_MAX_AGE_MS = 5 * 60 * 1000;
void initializeGifViewer();
async function initializeGifViewer() {
const content = document.getElementById("content");
if (!content) {
return;
}
try {
const gifData = await readStoredGifData();
validateGifData(gifData);
const blobUrl = createGifBlobUrl(gifData.base64);
renderGifPreview(content, blobUrl, gifData.filename);
document.title = gifData.filename;
window.addEventListener(
"unload",
() => URL.revokeObjectURL(blobUrl),
{ once: true },
);
await chrome.storage.local.remove(GIF_STORAGE_KEY);
} catch (error) {
renderErrorState(content, error);
console.error("[GIF Viewer] Error:", error);
}
}
async function readStoredGifData() {
const result = await chrome.storage.local.get(GIF_STORAGE_KEY);
return result.exportedGifData;
}
function validateGifData(gifData) {
if (
!gifData ||
typeof gifData.base64 !== "string" ||
typeof gifData.filename !== "string"
) {
throw new Error("No GIF data found. The export may have expired.");
}
if (Date.now() - gifData.timestamp > GIF_MAX_AGE_MS) {
throw new Error("GIF data expired. Please export again.");
}
}
function createGifBlobUrl(base64) {
const bytes = decodeBase64(base64);
const blob = new Blob([bytes], { type: "image/gif" });
return URL.createObjectURL(blob);
}
function decodeBase64(base64) {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let index = 0; index < binaryString.length; index += 1) {
bytes[index] = binaryString.charCodeAt(index);
}
return bytes;
}
function renderGifPreview(content, blobUrl, filename) {
const link = document.createElement("a");
link.href = blobUrl;
link.download = filename;
const image = document.createElement("img");
image.src = blobUrl;
image.alt = filename;
link.appendChild(image);
content.replaceChildren(link);
}
function renderErrorState(content, error) {
const errorBox = document.createElement("div");
errorBox.className = "error";
errorBox.textContent = getErrorMessage(error);
content.replaceChildren(errorBox);
}
function getErrorMessage(error) {
return error instanceof Error ? error.message : String(error);
}