如何在JavaScript中记录获取的网络资源? [英] How to log fetched network resources in JavaScript?

查看:187
本文介绍了如何在JavaScript中记录获取的网络资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有方法可以访问浏览器请求的资源列表(在此Chrome检查器的网络面板中找到的资源列表)?



我希望能够遍历这些获取的资源以显示已被访问的域名,如:

  for(var i = 0; i< window.navigator.resources.length ; i ++){
var resource = window.navigator.resources [i];
console.log(资源); // =>例如`{domain:www.google-analytics.com,名称:ga.js}`
}

或者,也许有一些事件需要编写处理程序,例如:

  window.navigator .onrequest = function(resource){
console.log(resource); // =>例如`{domain:www.google-analytics.com,名称:ga.js}`
}

它不需要跨浏览器工作,甚至不需要使用客户端JavaScript。只要能够以任何方式访问这些信息就可以工作(也许有一些方法可以使用phantomjs或者通过shell / node脚本观察网络流量)。任何想法?

解决方案

您可以这样做,但您需要使用Chrome扩展程序。



Chrome扩展程序有很多沙盒式安全功能。 Chrome扩展程序和网页之间的通信是一个多步骤的过程。以下是我在最后提供的一个完整示例中提供的最简洁的解释:


  1. Chrome扩展程序可以完全访问 chrome。* APIs ,但Chrome扩展程序无法直接与网页JS进行通信,也无法直接与Chrome扩展程序进行通信。


  2. 为了弥补Chrome扩展与网页之间的差距,您需要使用 内容脚本 。内容脚本本质上是JavaScript,它被注入到目标网页的窗口范围内。内容脚本不能调用函数,也不能访问由网页JS创建的变量,但它们共享对同一个DOM 的访问权限,因此也是事件。


  3. 由于不允许直接访问变量和调用函数,因此网页和内容脚本可以进行通信的唯一方式是通过发布自定义事件


例如,如果我想从Chrome扩展程序传递消息到页面,我可以这样做:



'p> content_script.js

 的document.getElementById( theButton)。的addEventListener( 点击,函数(){
window.postMessage({type:TO_PAGE,text:Hello from the extension!},*);
},false);

web_page.js

  window.addEventListener(message,function(event){
//我们只接受来自自己的消息
if(event.source!= window)
return; (event.data.type&&;(event.data.type ==TO_PAGE)){
alert(从内容脚本接收到:+事件。 data.text);
}
},false);

`4。现在您可以从内容脚本向网页发送消息,现在您需要Chrome扩展程序收集所需的所有网络信息。您可以通过几个不同的模块完成此操作,但最简单的选项是 webRequest 模块(参见下面的background.js)。



`5。使用消息传递将网络请求的信息转发给内容脚本,然后到网页JavaScript。



从视觉上来说,你可以这样想:



完整示例:



前三个文件包含您的Google Chrome浏览器扩展程序,最后一个文件是要上传到 http:// 某处的网站空间。



icon.png



使用任何16x16 PNG文件。



manifest.json

  {
name:webRequest Logging,
description:显示网页上的网络日志,
version:0.1,
权限:[
标签,
调试器,
webRequest,
http:// * / *

background:{
scripts:[background.js]
},
browser_action:{
default_icon:icon.png,
default_title:webRequest Logging
},
content_scripts:[
{
matches:[http:// * / *],
js:[content_script.js]
}
],
manifest_version:2
}

background.js

  var aNetworkLog = []; 

chrome.webRequest.onCompleted.addListener(函数(oCompleted){
变种sCompleted = JSON.stringify(oCompleted);
aNetworkLog.push(sCompleted);
}
,{url:[http:// * / *]}
);

chrome.extension.onConnect.addListener(function(port){
port.onMessage.addListener(function(message){
if(message.action ==getNetworkLog ){
port.postMessage(aNetworkLog);
}
});
});

content_script.js

  var port = chrome.extension.connect({name:'test'}); 

的document.getElementById( theButton)的addEventListener( 点击,函数(){

port.postMessage({行动: getNetworkLog});

},false);

port.onMessage.addListener(函数(MSG){
的document.getElementById( outputDiv)的innerHTML = JSON.stringify(MSG);
});

并在网页中使用以下内容(以您想要的名称命名):

 <!doctype html> 
< html>
< head>
< title> webRequest Log< / title>
< / head>
< body>
< input type =buttonvalue =检索webRequest日志id =theButton>
< div id =outputDiv>< / div>
< / head>
< / html>


Is there a way to access the list of resources that the browser requested (the ones found in this Chrome inspector's network panel)?

I would like to be able to iterate through these fetched resources to show the domains that have been accessed, something like:

for (var i = 0; i < window.navigator.resources.length; i++) {
  var resource = window.navigator.resources[i];
  console.log(resource); //=> e.g. `{domain: "www.google-analytics.com", name: "ga.js"}`
}

Or, maybe there is some event to write a handler for, such as:

window.navigator.onrequest = function(resource) {
  console.log(resource); //=> e.g. `{domain: "www.google-analytics.com", name: "ga.js"}`
}

It doesn't need to work cross browser, or even be possible using client-side JavaScript. Just being able to access this information in any way would work (maybe there's some way to do this using phantomjs or watching network traffic from a shell/node script). Any ideas?

解决方案

You can do this, but you will need to use Chrome extensions.

Chrome extensions have a lot of sandbox-style security. Communication between the Chrome extension and the web page is a multi-step process. Here's the most concise explanation I can offer with a full working example at the end:

  1. A Chrome extension has full access to the chrome.* APIs, but a Chrome extension cannot communicate directly with the web page JS nor can the web page JS communicate directly with the Chrome extension.

  2. To bridge the gap between the Chrome extension and the web page, you need to use a content script . A content script is essentially JavaScript that is injected at the window scope of the targeted web page. The content script cannot invoke functions nor access variables that are created by the web page JS, but they do share access to the same DOM and therefore events as well.

  3. Because directly accessing variables and invoking functions is not allowed, the only way the web page and the content script can communicate is through firing custom events.

For example, if I wanted to pass a message from the Chrome extension to the page I could do this:

content_script.js

document.getElementById("theButton").addEventListener("click", function() {
    window.postMessage({ type: "TO_PAGE", text: "Hello from the extension!" }, "*");
}, false);

web_page.js

window.addEventListener("message", function(event) {
    // We only accept messages from ourselves
    if (event.source != window)
      return;

    if (event.data.type && (event.data.type == "TO_PAGE")) {
      alert("Received from the content script: " + event.data.text);
    }
}, false);

`4. Now that you can send a message from the content script to the web page, you now need the Chrome extension gather up all the network info you want. You can accomplish this through a couple different modules, but the most simple option is the webRequest module (see background.js below).

`5. Use message passing to relay the info on the web requests to the content script and then on to the web page JavaScript.

Visually, you can think of it like this:

Full working example:

The first three files comprise your Google Chrome Extension and the last file is the HTML file you should upload to http:// web space somewhere.

icon.png

Use any 16x16 PNG file.

manifest.json

{
  "name": "webRequest Logging",
  "description": "Displays the network log on the web page",
  "version": "0.1",
  "permissions": [
    "tabs",
    "debugger",
    "webRequest",
    "http://*/*"
  ],
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "webRequest Logging"
  },
   "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["content_script.js"]
    }
  ],
  "manifest_version": 2
}

background.js

var aNetworkLog = [];

chrome.webRequest.onCompleted.addListener(function(oCompleted) {
            var sCompleted = JSON.stringify(oCompleted);
            aNetworkLog.push(sCompleted);
        }
        ,{urls: ["http://*/*"]}
 );

chrome.extension.onConnect.addListener(function (port) {
    port.onMessage.addListener(function (message) {
        if (message.action == "getNetworkLog") {
            port.postMessage(aNetworkLog);
        }
    });
});

content_script.js

var port = chrome.extension.connect({name:'test'});

document.getElementById("theButton").addEventListener("click", function() {

    port.postMessage({action:"getNetworkLog"});

}, false);

port.onMessage.addListener(function(msg) {
  document.getElementById('outputDiv').innerHTML = JSON.stringify(msg);
});

And use the following for the web page (named whatever you want):

<!doctype html>
<html>
<head>
    <title>webRequest Log</title>
</head>
<body>
    <input type="button" value="Retrieve webRequest Log" id="theButton">
    <div id="outputDiv"></div>
</head>
</html>

这篇关于如何在JavaScript中记录获取的网络资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆