我的GitHub
0%

无星的前端之旅(三十一)——Chrome插件监听网络请求

背景

需要监听某个网络请求

并根据body信息做出判断

将结果展示到插件页面

manifest.json

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
{
"manifest_version": 2,
"name": "xxx",
"version": "0.0.1",
"description": "xxx",
"permissions": [
"contextMenus",
"cookies",
"storage",
"history",
"webRequest",
"webRequestBlocking",
"*://*/*",
"http://www.baidu.com/*",
"tabs"
],

"content_scripts": [
{
"matches": [
"http://www.baidu.com/*"
],
"js": [
"content.js"
],
"run_at": "document_start",
"all_frames": true
}
],
"browser_action": {
"default_title": "xxx",
"default_popup": "popup.html"
},
"icons": {
"16": "icons/icon.png",
"32": "icons/icon.png",
"48": "icons/icon.png",
"128": "icons/icon.png"
},
"web_accessible_resources": [
"injected.js"
]
}

injected.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
(function () {
let origFetch = window.fetch;
window.fetch = async function (...args) {
const response = await origFetch(...args);
// console.log('fetch request:', args);

const [url] = args

const data = await response
.clone()
.json() // 此处需要根据不同数据调用不同方法
.catch(err => console.error(err));

// 对于二进制大文件可以创建为URL(blob:开头),供其它脚本访问
//sessionStorage['wave'] = URL.createObjectURL(data); // 插件需要添加'storage'权限
// // 只监听某些地址
if (url === './xx/xx/xx' && data.respData.corpOther.includes('xxxx')) {
window.postMessage({ type: 'type', data: data.respData }, '*'); // send to content script
}

return response;
}
})();
// 下面为xhr,需要则打开
(function (xhr) {

var XHR = XMLHttpRequest.prototype;

var open = XHR.open;
var send = XHR.send;

XHR.open = function (method, url) {
this._method = method;
this._url = url;
return open.apply(this, arguments);
};

XHR.send = function (postData) {
// console.log('xhr request:', this._method, this._url, postData);
this.addEventListener('load', function () {
// sessionStorage['key'] = JSON.stringify(response); // 插件需要添加'storage'权限
// document.cookie
// localStorage['key']
// console.log('xhr监听完成');
window.postMessage({ type: 'xhr', data: this.response }, '*'); // 将响应发送到 content script
});
return send.apply(this, arguments);
};
})(XMLHttpRequest);

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
console.log('编号查询插件注入成功');

// inject injected script
let s = document.createElement('script');
s.src = chrome.runtime.getURL('injected.js');
s.onload = function () {
this.remove();
};
(document.head || document.documentElement).appendChild(s);

// receive message from injected script
window.addEventListener('message', function (e) {
// 判断类型
const type = e.data.type
if (type === 'ocr') {
chrome.storage.local.get(["result"], function (result) {
console.log(123);
const data = result.result ?? ''
const tmp = data + e.data.data + '\n'
chrome.storage.local.set({ result: tmp })
})
}
});

popup.html

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
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>xxxx</title>
<style>
.main {
height: 300px;
width: 500px;
}

.main .textarea {
width: 300px;
height: 200px;
}
</style>
</head>

<body class="main">
<h1>以下为请求结果</h1>
<button id="clearButton">清空结果</button>
<button id="getResultButton">获取结果</button>
</br>
<textarea id="result" class="textarea"></textarea>
<script src="./popup.js"></script>
</body>

</html>

popup.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

function clear() {
chrome.storage.local.set({ "result": "" }, function () {
document.getElementById('result').value = '';
})
}

function getResult() {
chrome.storage.local.get(["result"], function (result) {
const data = result.result ?? ''
document.getElementById('result').value = data;
})
}
const button = document.getElementById('clearButton')
button.onclick = clear

const button2 = document.getElementById('getResultButton')
button2.onclick = getResult

getResult()

我是阿星,阿星的阿,阿星的星!