-
Notifications
You must be signed in to change notification settings - Fork 8
/
content-script.js
53 lines (46 loc) · 1.43 KB
/
content-script.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
/* eslint-disable functional/no-expression-statement */
/* eslint-disable functional/no-conditional-statement */
// TODO fix this
/* eslint-disable @typescript-eslint/strict-boolean-expressions */
/**
* @param {EventTarget | null} node
* @return {HTMLAnchorElement | null}
*/
const clickedLink = (node) => {
if (node instanceof HTMLAnchorElement) {
return node;
} else if (node instanceof Node) {
return clickedLink(node.parentNode);
} else {
return null;
}
};
window.addEventListener(
"click",
(e) => {
const wasMiddleClick = e.button === 1;
const wasModifiedLeftClick =
e.button === 0 && (e.metaKey || e.ctrlKey || e.shiftKey);
if (wasMiddleClick || wasModifiedLeftClick) {
const target = clickedLink(e.target);
const href = target && target.href && target.href.trim();
const hrefAttr = target && target.getAttribute("href");
const shouldHandleClick =
href && hrefAttr && !href.startsWith("javascript:") && hrefAttr !== "#";
if (target !== null && shouldHandleClick) {
e.preventDefault();
e.stopImmediatePropagation();
/** @type {Message} */
const message = {
url: target.href,
metaKey: e.metaKey,
ctrlKey: e.ctrlKey,
shiftKey: e.shiftKey,
};
// eslint-disable-next-line @typescript-eslint/no-floating-promises
chrome.runtime.sendMessage(message);
}
}
},
true
);