-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpopup.js
252 lines (232 loc) · 8.55 KB
/
popup.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Make sure this extension works universally.
self.browser = self.browser || self.chrome;
import patternsFunc from './patternsFunc.js';
import html2canvas from './html2canvas.esm.js';
const CANONICAL = 'https://goo.gle/how-fugu-is-the-web';
const MAX_DISPLAY_URL_LENGTH = 50;
// DOM references.
const ul = document.querySelector('ul');
const shareButton = document.querySelector('#share');
const downloadButton = document.querySelector('#download');
const heading = document.querySelector('h1');
const paragraph = document.querySelector('p');
const ol = document.querySelector('ol');
// This needs to be prepared before the share button is clicked,
// else, the user gesture would be consumed by the time the PNG
// image can be created.
let blob;
// Runs the feature detection functions for all Fugu features.
const supported = await patternsFunc();
const shortenURL = (url) => {
return `${url.hostname}${
url.pathname.length > MAX_DISPLAY_URL_LENGTH
? `${url.pathname.substring(0, MAX_DISPLAY_URL_LENGTH)}…`
: url.pathname
}`;
};
// Render the message HTML. The message comes from the content script.
const displayMessage = (message, tab) => {
if (!message.data) {
return;
}
// Translated strings.
document.title = browser.i18n.getMessage('extName');
heading.textContent = document.title;
const url = new URL(tab.url);
paragraph.innerHTML = `${browser.i18n.getMessage('detectedAPIs')} <a href="${
tab.url
}">${shortenURL(url)}</a>:`;
document.querySelector('#made-by').textContent =
browser.i18n.getMessage('madeBy');
document.querySelector('#source-code').textContent =
browser.i18n.getMessage('sourceCode');
shareButton.textContent = browser.i18n.getMessage('share');
downloadButton.textContent = browser.i18n.getMessage('download');
ul.innerHTML = '';
for (const [key, values] of Object.entries(message.data)) {
const li = document.createElement('li');
ul.append(li);
const h2 = document.createElement('h2');
h2.textContent = `${key}:`;
li.append(h2);
const span = document.createElement('span');
li.append(span);
span.innerHTML = supported[key]
? `<span class="emoji">✅</span> ${browser.i18n.getMessage('supported')} `
: supported[key] === undefined
? `<span class="emoji">🤷</span> ${browser.i18n.getMessage('unknown')} `
: `<span class="emoji">🚫</span> ${browser.i18n.getMessage(
'notSupported',
)} `;
const a = document.createElement('a');
li.append(a);
a.href = values[0].documentation;
a.classList.add('help');
a.innerHTML = browser.i18n.getMessage('details');
const nestedUl = document.createElement('ul');
nestedUl.classList.add('nested');
li.append(nestedUl);
values.forEach((value) => {
const nestedLi = document.createElement('li');
nestedUl.append(nestedLi);
const a = document.createElement('a');
nestedLi.append(a);
a.href = `${value.href}#:~:text=${encodeURIComponent(
value.matchingText,
)}`;
const tabOrigin = new URL(tab.url).origin;
const resourceURL = new URL(value.url);
a.textContent =
tabOrigin === resourceURL.origin
? (resourceURL.pathname + resourceURL.search).length >
MAX_DISPLAY_URL_LENGTH
? resourceURL.pathname + resourceURL.search + '…'
: resourceURL.pathname + resourceURL.search
: value.url.length > MAX_DISPLAY_URL_LENGTH
? value.url.substring(0, MAX_DISPLAY_URL_LENGTH) + '…'
: value.url;
});
}
};
shareButton.addEventListener('click', async () => {
browser.tabs.query({ active: true, currentWindow: true }, ([tab]) => {
const url = tab.url;
browser.action.getBadgeText({ tabId: tab.id }, async (text) => {
const numAPIs = Number(text);
const message = `🙋 I just found an app…
👉 ${url} 👈
…that uses ${numAPIs} Fugu 🐡 API${numAPIs === 1 ? '' : 's'}!
How Fugu 🐡 is the Web? Find out by installing the extension from ${CANONICAL} and share on #HowFuguIsTheWeb!`.trim();
if ('share' in navigator) {
const shareData = {
text: message,
title: '',
blob,
};
// The fallback when rich sharing isn't available.
const shareTextOnly = async (shareData) => {
delete shareData.blob;
try {
await navigator.share(shareData);
} catch (err) {
if (err.name !== 'AbortError') {
console.error(err.name, err.message);
}
}
};
// Try rich sharing first.
const share = async (shareData) => {
if (!('canShare' in navigator) || !navigator.canShare(shareData)) {
return shareTextOnly(shareData);
}
try {
await navigator.share(shareData);
} catch (err) {
if (err.name !== 'AbortError') {
console.error(err.name, err.message);
delete shareData.files;
shareTextOnly(shareData);
}
}
};
const files = [
new File([blob], 'how-fugu-is-the-web.png', { type: blob.type }),
];
shareData.files = files;
share(shareData);
} else {
const shareURL = new URL('https://twitter.com/intent/tweet');
const params = new URLSearchParams();
params.append('text', message);
shareURL.search = params;
window.open(shareURL, '_blank', 'popup,noreferrer,noopener');
}
});
});
});
const createScreenshot = async (url) => {
const clone = document.body.querySelector('main').cloneNode(true);
const footer = clone.querySelector('footer');
const ol = clone.querySelector('ol');
ol.remove();
const computedStyle = getComputedStyle(document.documentElement);
const mainColor = computedStyle.getPropertyValue('--main-color');
const mainBackgroundColor = computedStyle.getPropertyValue(
'--main-background-color',
);
const linkColor = computedStyle.getPropertyValue('--link-color');
document.documentElement.style.color = mainColor;
clone.style.color = mainColor;
clone.style.backgroundColor = mainBackgroundColor;
clone.querySelectorAll('a').forEach((a) => (a.style.color = linkColor));
clone.querySelectorAll('button').forEach((button) => {
button.style.display = 'none';
});
const link = footer.querySelector('a:nth-of-type(2)');
link.textContent = CANONICAL;
link.href = CANONICAL;
footer.innerHTML = footer.innerHTML.replace(
browser.i18n.getMessage('sourceCode'),
'<br/>Install the extension from',
);
document.body.append(clone);
const canvas = await html2canvas(clone, {
backgroundColor: mainBackgroundColor,
logging: false,
windowWidth: 700,
});
clone.remove();
blob = await fetch(canvas.toDataURL()).then((r) => r.blob());
return blob;
};
// Receives messages from the content script.
browser.runtime.onMessage.addListener((message, sender) => {
browser.tabs.query({ active: true, currentWindow: true }, ([tab]) => {
if (message.type === 'return-results') {
displayMessage(message, tab);
setTimeout(async () => {
blob = await createScreenshot(tab.url);
}, 0);
/Apple/.test(navigator.vendor)
? shareButton.classList.add('ios')
: shareButton.classList.add('others');
if ('share' in navigator) {
downloadButton.style.display = 'none';
} else {
downloadButton.style.display = 'inline-block';
ol.style.visibility = 'visible';
// Fallback to use Twitter's Web Intent URL, as outlined in
// https://web.dev/patterns/advanced-apps/share/.
if (!downloadButton.dataset.eventListenerAdded) {
downloadButton.addEventListener('click', () => {
const a = document.createElement('a');
a.download = 'how-fugu-is-the-web.png';
a.style.display = 'none';
a.href = URL.createObjectURL(blob);
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.remove(a);
URL.revokeObjectURL(a.href);
}, 30 * 1000);
});
downloadButton.dataset.eventListenerAdded = true;
}
}
shareButton.style.display = 'inline-block';
}
});
});
// Request the results from the injected content script.
browser.tabs.query({ active: true, currentWindow: true }, ([tab]) => {
// Ask the content script.
browser.tabs.sendMessage(
tab.id,
{ type: 'request-results', data: tab.url },
() => {
if (browser.runtime.lastError) {
return;
}
},
);
});