我有一种情况,我需要监视网页发出的所有网络请求。当我指的是所有网络请求时,我的意思是绝对所有,即:
在后一种情况下,如果我谈论以下场景:
<!-- Let's say my web page is hosted at https://example.com/ -->
<html>
...
<script src="https://otherdomain.com/somescript.js"></script>
...
</html>
如果
somescript.js
从网络、其自己的域或任何其他域下载内容,我也需要对其进行监控。
这可能吗?
到目前为止,我尝试使用 Service Worker,它确实有效,至少在某种程度上是这样。令人惊讶的是,我的服务人员实际上并没有看到某些请求。它的注册范围是
/
。
只需在目标脚本之前添加猴子补丁
fetch
和 XMLHttpRequest.prototype
。
fetch
的示例:
const _fetch = window.fetch;
const prop = Object.getOwnPropertyDescriptor(window, 'fetch');
let events = [];
prop.value = function () {
console.log('fetch:', ...arguments);
const out = _fetch.apply(window, arguments);
out.then(function(response) {
const _json = response.json;
response.json = function () {
const out = _json.call(response);
out.then(data => {
console.log(data);
return data;
});
return out;
}
return response;
});
return out;
}
Object.defineProperty(window, 'fetch', prop);
fetch('https://jsonplaceholder.typicode.com/todos/1').then(r => r.json());