-
Notifications
You must be signed in to change notification settings - Fork 8
/
logic.js
83 lines (81 loc) · 2.92 KB
/
logic.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
// message.to must match this or messages from the background will be ignored
const ME = "logic";
// a list of commands we are willing to carry out when the background process asks
const cmd = {
// render the altered image
renderAlteredImage: message => {
// filter an array of all images on the page
Array.from(document.getElementsByTagName("IMG")).filter(img => {
// find all images matching the source of the one we right-clicked
if (img.src && img.src === message.args.oldImageSrc) {
// swap in the updated source
img.src = message.args.newImageSrc;
}
});
},
// open an iframe overlay
openOverlay: message => {
// never open overlays inside iframes
if (window.self === window.top) {
// build an iframe
const overlayToOpen = document.createElement("IFRAME");
// shall we hide the overlay?
if (message.args.hidden) {
// make it tiny
overlayToOpen.height = overlayToOpen.width = "1";
// get ready to move it outside the visible window
overlayToOpen.style.position = "absolute";
// move it outside the visible window
overlayToOpen.style.left = overlayToOpen.style.top = "-100px";
}
// give it the ID generated by the background
overlayToOpen.id = message.args.id;
// when we're loaded, ask it to render
overlayToOpen.onload = () => {
// bounce a message through background process
chrome.runtime.sendMessage({
// this is the overlay name, not the iframe element ID
to: message.args.overlay,
// render
cmd: "render",
// send argument objects
args: message.args
});
};
// get the full path, which will be chrome-extension://deadbeefdeadbeefdeadbeef/html/overlayname.html
overlayToOpen.src = chrome.runtime.getURL(
// don't forget to list /html/overlayname.html in manifest.web_accessible_resources
"/html/" + message.args.overlay + ".html"
);
// append to the DOM so it will start loading
document.body.appendChild(overlayToOpen);
}
},
// close an iframe overlay
closeOverlay: message => {
// overlays should not have rendered in iframes
if (window.self === window.top) {
// do we know the element ID to close?
if (message.args.id) {
// look for it
const overlayToClose = document.getElementById(message.args.id);
// did we find it?
if (overlayToClose) {
// close it
overlayToClose.parentNode.removeChild(overlayToClose);
}
}
}
}
};
// listen for messages from the background
chrome.runtime.onMessage.addListener(message => {
// is the message for us?
if (message.to && message.to === ME) {
// do we have a valid command?
if (message.cmd && typeof cmd[message.cmd] === "function") {
// run it, passing the full message object
cmd[message.cmd](message);
}
}
});