-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathbackground.js
109 lines (86 loc) · 2.84 KB
/
background.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Chrome automatically creates a background.html page for this to execute.
// This can access the inspected page via executeScript
//
// Can use:
// chrome.tabs.*
// chrome.extension.*
var version = "1.0";
// When devtools opens, this gets connected
chrome.extension.onConnect.addListener(function (port) {
var extensionListener = function (message, sender, sendResponse) {
if (message.action === "downloadHARlog") {
port.postMessage(message);
} else {
sendResponse(message);
}
}
// Listens to messages sent from the panel
chrome.extension.onMessage.addListener(extensionListener);
port.onDisconnect.addListener(function(port) {
chrome.extension.onMessage.removeListener(extensionListener);
});
});
var gTabId;
var logData = [];
function onEvent(debuggeeId, message, params) {
if (gTabId != debuggeeId.tabId)
return;
logData.push(params)
}
function onAttach(tabId) {
gTabId = tabId;
if (chrome.runtime.lastError) {
return;
}
// use Log.enable and go from there
chrome.debugger.sendCommand({ tabId: tabId }, "Log.enable");
chrome.debugger.onEvent.addListener(onEvent);
setTimeout(() => {
let harBLOB = new Blob([JSON.stringify(logData)]);
let url = URL.createObjectURL(harBLOB);
chrome.downloads.download({
url: url
});
// cleanup after downloading file
chrome.debugger.sendCommand({ tabId: tabId }, "Log.disable");
chrome.debugger.detach({ tabId: tabId });
gTabId = undefined;
logData = [];
}, 1000);
}
// is devtools open
var openCount = 0;
var isDevToolsOpen = false;
// Always return true for async connections for chrome.runtime.onConnect.addListener
chrome.runtime.onConnect.addListener(function (port) {
if (port.name == "devtools-page") {
if (openCount == 0) {
isDevToolsOpen = true
// alert("DevTools window opening.");
}
openCount++;
port.onDisconnect.addListener(function(port) {
openCount--;
if (openCount == 0) {
isDevToolsOpen = false
}
});
}
return true;
});
// messages from popup.js
// Always return true for async connections for chrome.runtime.onConnect.addListener
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
let info = {}
info.request = JSON.stringify(request)
info.sender = JSON.stringify(sender)
info.sendResponse = JSON.stringify(sendResponse)
if(request.action === "getDevToolsStatus"){
// response needs to be in JSON format
sendResponse({data: isDevToolsOpen})
} else if (request.action === "getConsoleLog"){
chrome.debugger.attach({tabId:request.tabId}, version,
onAttach.bind(null, request.tabId));
}
return true;
});