【发布时间】:2019-07-20 14:17:08
【问题描述】:
我正在 Chrome DevTools(或任何等效工具)中寻找一种方法来控制我的 Web 应用程序完成的 HTTP 请求:
我想在执行之前批准 HTTP 请求,或者让它们以意想不到的方式失败(给它状态 500 或其他东西)。
用法示例:测试意外行为
有谁知道实现这一目标的方法。
【问题讨论】:
标签: api google-chrome http devtools
我正在 Chrome DevTools(或任何等效工具)中寻找一种方法来控制我的 Web 应用程序完成的 HTTP 请求:
我想在执行之前批准 HTTP 请求,或者让它们以意想不到的方式失败(给它状态 500 或其他东西)。
用法示例:测试意外行为
有谁知道实现这一目标的方法。
【问题讨论】:
标签: api google-chrome http devtools
您可以使用Requestly Chrome 扩展来重定向、取消、阻止、修改标头……的请求。
在执行之前批准请求,例如对于 AJAX 请求,创建重定向规则并将其指向静态 JSON 文件或其他脚本。
要阻止请求,请使用取消请求功能并设置自定义模式。
【讨论】:
我看到了在客户端实现此目标的两种可能的解决方案:
使用抽屉中的请求阻止面板(打开 Chrome DevTools -> Esc -> '...' -> 请求阻止 这完全是开箱即用的,适用于大多数“离线优先”的用例。
使用服务人员。它们基本上是一种代理请求和单独响应的方式(例如,通过 500-er 响应)。您可能希望通过使用 Chrome Devtools Snippets(打开 Chrome DevTools -> Sources -> Snippets)来启用/禁用此类调试功能,因为您不希望您的请求一直失败:)
首先你需要像这样注册你的 serviceworker:
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('/path-to-service-worker.js').then(function(registration) {
// registration successful
}).catch(function(err) {
// registration failed
});
}
然后重新加载浏览器(或在 DevTools -> 应用程序 -> Service Workers 中安装您的 service-worker),以便您的 service-worker.js 处于活动状态,可以监听 'fetch' 事件并代理此请求像这样的域:
self.addEventListener('fetch', function(event) {
// this will set a breakpoint in chrome devtools, allowing you to manually edit the response
debugger;
// alternatively you could reponse with an error response like this:
event.respondWith(
new Response(null, {
status: 500
})
);
});
旁注:由于浏览器中的安全限制,服务人员只能在 https 和 localhost 上工作。
更多信息: https://developer.mozilla.org/en-US/docs/Web/API/Response/Response https://developers.google.com/web/fundamentals/primers/service-workers/
【讨论】: