使用JavaScript/jQuery跟踪浏览器发送的HTTP请求

10

使用JavaScript或jQuery,是否有一种方法可以跟踪网页发送的HTTP请求(包括标头、参数等)?我想要实现的功能类似于Google Chrome开发者控制台的“网络”选项卡的功能。我找到的所有解决方案都是跟踪Ajax请求或使用JavaScript(使用XMLHttpRequest对象)进行的请求。这个功能应该也支持跨浏览器。


https://developer.chrome.com/extensions/devtools_network - Praveen Kumar Purushothaman
1
作为扩展程序还是在浏览器中运行的代码?在浏览器中运行的代码将无法访问它。 - epascarello
1
实际上我想要的只是一个 JavaScript 函数来完成这个任务,而不是一个扩展程序。我需要跟踪仅由包含此 JavaScript 文件的网站发送的请求。 - Aruna Tebel
@tibzon 看看我的第一种和第三种方法! - Praveen Kumar Purushothaman
@Mitul,实际上我想要的是以编程方式完成相同的事情,我需要跟踪所有请求并将它们存储在本地。 - Aruna Tebel
显示剩余4条评论
3个回答

2
你有三个选择。
  1. Make sure you know all the places where a request can get fired, and attach an event to it, say RequestFired. And bind the onRequestFired event in your JavaScript / jQuery code.

  2. Go through the Network Developers document or each browser and based on the browser, execute it. This feature may not be available in older browsers like Internet Explorer 7 and 8.

  3. If it is for a particular server, read the Server Log using a server side script and access it using an endpoint. You can use long polling method and fetch the contents of the log, may be this way:

        // jQuery
        $(document).ready(function () {
          setInterval (function () {
            $("#log").load("/path/to/endpoint.log");
          }, 5000);
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <h3>Logs</h3>
        <div id="log"></div>


1

你无法追踪所有的东西。

例如,Xmlhttprequest 中的一些调用是透明的(301 HTTP 状态码),无法由 javascript 客户端处理。

请参阅 XMLHTTrequest 规范: http://www.w3.org/TR/XMLHttpRequest/#infrastructure-for-the-send-method

这是其中的几个原因之一。如果你想追踪一个“网页”的请求,最好使用该浏览器的开发工具或数据包捕捉。

在用户体验方面,只能做出非常有限的事情。


1
如果您正在使用像AngularJS这样的框架实现单页Web应用程序,则可以通过使用HTTP 拦截器来完成。除此之外,您只能跟踪Ajax请求,而无法跟踪JavaScript请求。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接