-
Notifications
You must be signed in to change notification settings - Fork 8
/
content.js
76 lines (66 loc) · 2.92 KB
/
content.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
// Open links in new tab only when navigating to Bing or Google using the extension
if (location && location.href.indexOf("ds=1") >= 0) {
var head = document.getElementsByTagName("head")[0];
if (head) {
var base = document.createElement("base");
base.setAttribute("target", "_blank");
head.appendChild(base);
}
function receiver(event) {
if (event.origin.indexOf('-extension://') > 0 && event.data && event.data.type) {
switch (event.data.type) {
case "Load":
event.source.postMessage({
scroll: (document.documentElement.scrollWidth * 100) / document.documentElement.clientWidth,
height: document.documentElement.scrollHeight
}, event.origin);
// Listen to Ajax navigation
window.addEventListener("message", function(e) {
if (e.source === window && e.data.api) {
var d = e.data;
switch (d.api) {
case "pushState":
event.source.postMessage({ url: d.url }, event.origin);
break;
}
}
});
// Execute script in webpage context
var script = document.createElement("script");
var code = proxy();
script.innerText = code;
document.body.appendChild(script);
break;
case "Resize":
event.source.postMessage({
scroll: (document.documentElement.scrollWidth * 100) / document.documentElement.clientWidth,
height: document.documentElement.scrollHeight
}, event.origin);
break;
case "Scroll":
document.documentElement.scrollLeft = event.data.value;
break;
}
}
}
// Let the code within webpage context to communicate back to the extension
function proxy() {
var closure = () => {
var pushState = history.pushState;
history.pushState = function(state, title, url) {
pushState.apply(this, arguments);
window.postMessage({ api: "pushState", url: location.href }, "*");
};
};
return `(${closure.toString()})();`;
}
function load() {
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
links[i].setAttribute("target", "_blank");
links[i].setAttribute("rel", "opener");
}
}
window.addEventListener("message", receiver, false);
window.addEventListener("load", load, false);
}