forked from image4tools/Save-Image-as-Type
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
221 lines (211 loc) · 5.75 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
let messages;
// some old chrome doesn't support chrome.i18n.getMessage in service worker.
if (!chrome.i18n?.getMessage) {
if (!chrome.i18n) {
chrome.i18n = {};
}
chrome.i18n.getMessage = (key, args) => {
if (key == 'View_in_store') {
return 'View in store';
}
if (key == 'Save_as' && args?.[0]) {
return 'Save as ' + args[0];
}
return key;
};
}
function download(url, filename) {
chrome.downloads.download(
{ url, filename, saveAs: true },
function(downloadId) {
if (!downloadId) {
let msg = chrome.i18n.getMessage('errorOnSaving');
if (chrome.runtime.lastError) {
msg += ': \n'+ chrome.runtime.lastError.message;
}
notify(msg);
}
}
);
}
async function fetchAsDataURL(src, callback) {
if (src.startsWith('data:')) {
callback(null, src);
return;
}
fetch(src)
.then(res => res.blob())
.then(blob => {
if (!blob.size) {
throw 'Fetch failed of 0 size';
}
let reader = new FileReader();
reader.onload = async function(evt){
let dataurl = evt.target.result;
callback(null, dataurl);
};
reader.readAsDataURL(blob);
})
.catch(error => callback(error.message || error));
}
function getSuggestedFilename(src, type) {
//special for chrome web store apps
if(src.match(/googleusercontent\.com\/[0-9a-zA-Z]{30,}/)){
return 'screenshot.'+type;
}
if (src.startsWith('blob:') || src.startsWith('data:')) {
return 'Untitled.'+type;
}
let filename = src.replace(/[?#].*/,'').replace(/.*[\/]/,'').replace(/\+/g,' ');
filename = decodeURIComponent(filename);
filename = filename.replace(/[\x00-\x7f]+/g, function (s){
return s.replace(/[^\w\-\.\,@ ]+/g,'');
});
while(filename.match(/\.[^0-9a-z]*\./)){
filename = filename.replace(/\.[^0-9a-z]*\./g,'.');
}
filename = filename.replace(/\s\s+/g,' ').trim();
filename = filename.replace(/\.(jpe?g|png|gif|webp|svg)$/gi,'').trim();
if(filename.length > 32){
filename = filename.substr(0,32);
}
filename = filename.replace(/[^0-9a-z]+$/i,'').trim();
if(!filename){
filename = 'image';
}
return filename+'.'+type;
}
function notify(msg) {
if (msg.error) {
msg = (chrome.i18n.getMessage(msg.error) || msg.error) + '\n'+ (msg.srcUrl || msg.src);
}
}
function loadMessages() {
if (!messages) {
messages = {};
['errorOnSaving', 'errorOnLoading'].forEach(key => {
messages[key] = chrome.i18n.getMessage(key);
});
}
return messages;
}
async function hasOffscreenDocument(path) {
const offscreenUrl = chrome.runtime.getURL(path);
const matchedClients = await clients.matchAll();
for (const client of matchedClients) {
if (client.url === offscreenUrl) {
return true;
}
}
return false;
}
chrome.runtime.onInstalled.addListener(function () {
loadMessages();
['JPG','PNG','WebP'].forEach(function (type){
chrome.contextMenus.create({
"id" : "save_as_" + type.toLowerCase(),
"title" : chrome.i18n.getMessage("Save_as", [type]),
"type" : "normal",
"contexts" : ["image"],
});
});
chrome.contextMenus.create({
"id" : "sep_1",
"type" : "separator",
"contexts" : ["image"]
});
chrome.contextMenus.create({
"id" : "view_in_store",
"title" : chrome.i18n.getMessage("View_in_store"),
"type" : "normal",
"contexts" : ["image"],
});
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
let {target, op} = message || {};
if (target == 'background' && op) {
if (op == 'download') {
let {url, filename} = message;
download(url, filename);
} else if (op == 'notify') {
let msg = message.message;
if (msg && msg.error) {
let msg2 = chrome.i18n.getMessage(msg.error) || msg.error;
if (msg.src) {
msg2 += '\n'+ msg.src;
}
notify(msg2);
} else {
notify(message);
}
} else {
console.warn('unknown op: ' + op);
}
}
});
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
let {menuItemId, mediaType, srcUrl} = info;
let connectTab = () => {
// for old chrome v108-
let port = chrome.tabs.connect(
tab.id,
{
name: 'convertType',
frameId: info.frameId,
},
);
return port;
};
if (menuItemId.startsWith('save_as_')) {
if (mediaType=='image' && srcUrl) {
let type = menuItemId.replace('save_as_', '');
let filename = getSuggestedFilename(srcUrl, type);
loadMessages();
let noChange = srcUrl.startsWith('data:image/' + (type == 'jpg' ? 'jpeg' : type) + ';');
if (!chrome.offscreen) {
// for old chrome v108-
let frameIds = info.frameId ? [] : void 0;
await chrome.scripting.executeScript({
target: { tabId: tab.id, frameIds },
files: ["offscreen.js"], // content script and offscreen use the same file.
});
}
fetchAsDataURL(srcUrl, async function(error, dataurl) {
if (error) {
notify({error, srcUrl});
return;
}
// offscreen api need chrome v109+
if (!chrome.offscreen) {
// for old chrome v108-
let port = connectTab();
await port.postMessage({ op: noChange ? 'download' : 'convertType', target: 'content', src: dataurl, type, filename });
return;
}
// for new chrome v109+
if (noChange) {
download(dataurl, filename);
return;
}
const offscreenSrc = 'offscreen.html'
if (!(await hasOffscreenDocument(offscreenSrc))) {
await chrome.offscreen.createDocument({
url: chrome.runtime.getURL(offscreenSrc),
reasons: ['DOM_SCRAPING'],
justification: 'Download a image for user',
});
}
await chrome.runtime.sendMessage({ op: 'convertType', target: 'offscreen', src: dataurl, type, filename });
});
return;
} else {
notify(chrome.i18n.getMessage("errorIsNotImage"));
}
return;
}
if (menuItemId == 'view_in_store') {
let url = "https://chrome.google.com/webstore/detail/save-image-as-type/" + chrome.i18n.getMessage("@@extension_id");
chrome.tabs.create({ url: url, index: tab.index + 1 });
return;
}
});