Chrome extension: Block page items before access

后端 未结 3 716
时光说笑
时光说笑 2020-12-02 00:25

I am trying to do block items on a webpage but I want to do that, before they are loaded. So, e.g., I could use

chrome.webRequest.onBeforeRequest.addListener(

相关标签:
3条回答
  • 2020-12-02 00:41

    I was able to achieve what i was trying to do. The solution does not necessarily need extensions anymore, but to setup a proxy this might be useful. Afterwards, the solution (for the specified problem above) is as follows:

    • Use a chrome extension to use a proxy, in this case, localhost
    • Setup a proxyscript, e.g. using python, to route all traffic (and maybe install certificates, so HTTPs traffic may be analyzed as well)
    • => Man-in-the-middle established, analyze traffic and modify if needed

    Yes, this is not really a solution to the problem of making a chrome extension do this somehow, but it is not possible yet (see https://bugs.chromium.org/p/chromium/issues/detail?id=104058).

    Best regards, mutilis

    0 讨论(0)
  • 2020-12-02 00:47

    You can use ServiceWorker to read original Response before returning content of original Response or new content.

    if ("serviceWorker" in navigator) {
      navigator.serviceWorker.register("sw.js").then(function(reg) {
        console.log("register", reg);
      }).catch(function(err) {
        console.log("err", err);
      });
    }
    

    self.addEventListener("fetch", function(event) {
      if (event.request.url == "/path/to/fetched/resource/") {
        console.log("fetch", event);
        event.respondWith(
          fetch(event.request).then(function(response) {
            return response.text()
              .then(function(text) {
                if (text === "abc123") {
                  return new Response("def456")
                } else {
                  return new Response(text)
                }
              })
          })
        );
      }
    });
    

    plnkr https://plnkr.co/edit/MXGSZN1i3quvZhkI7fqe?p=preview

    See What happens when you read a response?

    0 讨论(0)
  • 2020-12-02 00:51

    I believe you can use arraybuffers to read the content in real-time.

    Here's an example of loading a file / page into a buffer;

    var oReq = new XMLHttpRequest();
    oReq.open("GET", "/myfile.png", true);
    oReq.responseType = "arraybuffer";
    
    oReq.onload = function (oEvent) {
      var arrayBuffer = oReq.response; // Note: not oReq.responseText
      if (arrayBuffer) {
        var byteArray = new Uint8Array(arrayBuffer);
        for (var i = 0; i < byteArray.byteLength; i++) {
          // do something with each byte in the array
        }
      }
    };
    
    oReq.send(null);
    

    This is a piece of code found on the XMLHttpRequest documentation page. Link.

    0 讨论(0)
提交回复
热议问题