How to log fetched network resources in JavaScript?

后端 未结 2 538
别跟我提以往
别跟我提以往 2021-02-14 01:00

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

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 01:37

    Big shoutout to @Elliot B.

    I essentially used what he did but I wanted events to trigger in the content script rather than listeners triggering in the background. For whatever reason, I was unable to connect to the port from the background script so this is what I came up with.

    PS: you need jquery.js in the extension folder to make this work.

    manifest.json

    {
      "manifest_version": 2,
    
      "name": "MNC",
      "version": "0.0.1",
      "description": "Monitor Network Comms",
      "permissions":["webRequest","*://*/"],
      "content_scripts": [{
      "matches": [""],
      "run_at": "document_start",
      "js": ["content.js",
            "jquery.js"]
      }],
      "background": {
        "scripts": ["background.js"]
      }
    }
    

    background.js

    var aNetworkLog = [];
    
    chrome.webRequest.onResponseStarted.addListener(
      function(oCompleted) {
        var sCompleted = JSON.stringify(oCompleted);
        aNetworkLog.push(sCompleted);
      },{urls: ["https://*/*"]}
    );
    
    chrome.extension.onConnect.addListener(function (port) {
      chrome.webRequest.onResponseStarted.addListener(
        function(){
          port.postMessage({networkLog:JSON.stringify(aNetworkLog)});
        },{urls: ["https://*/*"]}
      );
      port.onMessage.addListener(function (message) {
        if (message.disconnect==true) {
          port.disconnect();
        }
      });
    });
    

    content.js

    div = $('').appendTo(document.body);
    var port = chrome.extension.connect({name:'networkLogging'});
    port.onMessage.addListener(function (message) {
      if (message.networkLog) {
        div[0].innerHTML = message.networkLog;
      }
    });
    observer = new WebKitMutationObserver(function(mutation,observer){
      JSON.parse(mutation[0]['target'].innerHTML).forEach(function(item){
        JSON.parse(item);
      })
    });
    observer.observe(div[0],{childList:true});
    

    This is definitely not the most efficient way of doing things but it works for me. Thought that I would add it in here just in case someone is needing it.

提交回复
热议问题