Chrome DevTools在执行前批准网络请求

时间:2019-02-26 23:12:14

标签: api google-chrome http devtools

我正在寻找一种在Chrome DevTools(或任何等效工具)中控制我的Web应用程序完成的HTTP请求的方法:

我想在执行之前批准HTTP请求,或者让它们以意外的方式失败(将其状态设置为500或类似)。

用法示例:测试意外行为

有人知道实现这一目标的方法吗?

2 个答案:

答案 0 :(得分:4)

我看到了两种在客户端实现此目标的可能解决方案:

  1. 使用抽屉中的“请求阻止”面板(打开Chrome DevTools-> Esc->'...'->请求阻止 enter image description here 这完全是开箱即用的,适用于大多数“离线优先”用例。

  2. 使用服务人员。从根本上讲,它们是代理请求并进行单独响应的一种方式(例如,通过响应500-er)。您可能希望通过使用Chrome Devtools代码段(打开Chrome DevTools->源代码->代码段)来启用/禁用这种调试功能,因为您不希望请求始终失败:)

首先,您需要像这样注册您的服务人员:

if('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/path-to-service-worker.js').then(function(registration) {
    // registration successful
  }).catch(function(err) {
    // registration failed
  });
}

然后重新加载浏览器(或在DevTools-> Application-> 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/

答案 1 :(得分:4)

您可以使用Requestly Chrome扩展程序来重定向,取消,阻止,修改标题...等请求。

enter image description here

在执行例如对于AJAX请求,请创建一个重定向规则,并将其指向静态JSON文件或其他脚本。

要阻止请求,请使用取消请求功能并设置自定义模式。