This repository has been archived by the owner on May 1, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontentscript.js
58 lines (42 loc) · 1.53 KB
/
contentscript.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
/*
*/
var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
var container = document.head||document.documentElement
//container.insertBefore(s, container.children[0])
//s.onload = function() {s.remove();};
var port = chrome.runtime.connect({name: "contentscript"});
port.postMessage({src: "contentScript",dst:"background"});
port.onMessage.addListener(function(msg) {
console.log("msg listened: " +JSON.stringify(msg));
window.postMessage({ //forward msg from background to webpage
"data":msg
}, "*");
});
chrome.runtime.onConnect.addListener(function(port) {
console.log("Connected ....." + port.name);
port.onMessage.addListener(function(msg) {
console.log("msg listened: " + JSON.stringify(msg));
})
})
//message from background
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
window.postMessage({ //forward msg from background to webpage
"data": request
}, "*");
});
// Event listener
window.addEventListener('message', function(e) {
//if (e.source != window)
// return;
console.log("contentscript.js: received message event:" + ", stringify msg.data: "+JSON.stringify(e.data) );
//outputObj(e)
port.postMessage({ //forward msg from webpage to background
src: "contentScript",
dst:"background",
data: e.data })
});