-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap.js
94 lines (73 loc) · 2.72 KB
/
swap.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
var cache = {};
function swapImage(img) {
var src = cache[img.naturalWidth + 'x' + img.naturalHeight];
if (!src) {
var canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var c = canvas.getContext("2d");
c.fillStyle = 'lightgrey';
c.fillRect(0, 0, canvas.width, canvas.height);
var fontSize = canvas.width * 0.15;
c.font = fontSize + 'px Monaco, monospace';
c.textAlign = 'center';
c.textBaseline = 'middle';
c.fillStyle = 'black';
c.fillText(canvas.width + ' x ' + canvas.height, canvas.width/2, canvas.height/2);
src = canvas.toDataURL();
cache[img.naturalWidth + 'x' + img.naturalHeight] = src;
}
var realSrc = img.src;
img.dataset.realSrc = realSrc;
img.src = src;
}
function swapImageWhenLoaded(img) {
if (img.naturalWidth === 0) {
var imageSwapHandler = function(e) {
var img = e.target;
img.removeEventListener(e.type, arguments.callee);
if (img.naturalWidth !== 0) {
swapImage(img);
}
};
img.addEventListener('load', imageSwapHandler);
} else {
swapImage(img);
}
}
function swapChildImages(node) {
var images = node.querySelectorAll('img:not([src^="data:image/png;"])');
for (var i = 0; i < images.length; i++) {
swapImageWhenLoaded(images[i]);
}
}
function startSwapping() {
swapChildImages(document);
new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++) {
var node = mutation.addedNodes[i];
if (node.querySelectorAll) {
swapChildImages(node);
}
}
if (mutation.attributeName && mutation.target.tagName == 'IMG' && mutation.target.src.indexOf("data:image/png;")) {
swapImageWhenLoaded(mutation.target);
}
});
}).observe(document, {childList: true, subtree: true, attributes: true, attributeFilter: ['src']});
}
function handleBackgroundCommand(request) {
if (!request) { return; }
switch(request.action) {
case 'swap-images':
startSwapping();
break;
case 'undo-swap-images':
window.location.reload();
break;
}
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { handleBackgroundCommand(request) });
// Handle page reloads by checking if we have to swap the images in the current tab.
chrome.runtime.sendMessage({action: 'init'}, function(response) { handleBackgroundCommand(response) });