-
-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathcontent.js
More file actions
64 lines (60 loc) · 2.13 KB
/
content.js
File metadata and controls
64 lines (60 loc) · 2.13 KB
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
//======================================================================
// Inner functions
//======================================================================
/**
* Send event to inject script
* @param {*} type event type defined on inject script
* @param {*} data data to send
*/
function sendEvent(type, data='') {
let detailObj = { type: type, data: data };
let evt = new CustomEvent('vpcomm', { bubbles: true, detail: detailObj });
console.log('[vp content] send from content - ', type, data, evt);
document.dispatchEvent(evt);
}
function checkScriptExists(url) {
return document.querySelectorAll(`script[src="${url}"]`).length > 0;
}
/**
* Inject file
*/
function injectFile() {
let url = chrome.runtime.getURL('inject.js');
console.log('[vp content] check inject file...')
if (checkScriptExists(url)) {
console.log('[vp content] inject file already exist!');
return false;
}
console.log('[vp content] inject file!');
// inject script
var s = document.createElement('script');
s.src = url;
s.onload = function() {
// send event to inject.js to send its url
var url = chrome.runtime.getURL('');
// var evt = new CustomEvent('vpcomm', { bubbles: true, detail: { type: 'sendBase', data: url } });
// document.dispatchEvent(evt);
sendEvent('sendBase', url);
};
(document.head || document.documentElement).appendChild(s);
return true;
}
//======================================================================
// Event listener - background <-> (content -> inject)
//======================================================================
function msgHandler(msg, sender) {
if (msg && msg.type) {
switch(msg.type) {
case "toggle":
injectFile();
sendEvent('toggle');
break;
default:
break;
}
}
}
chrome.runtime.onMessage.removeListener(msgHandler);
chrome.runtime.onMessage.addListener(msgHandler);
console.log('[vp content] content script executed!');
// End of file