Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - Chrome extension: Block page items before access

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(...);

And redirect/cancel the request. But i want to inspect the actual content of the request. What I am doing right now, is starting a XMLHttpRequest to load the url/object myself, inspect the content, and block it if necessary. However, the main problem is that in fact, not many objects are blocked. This means, that each object is loaded twice: Once for "my inspection" and once, after I said "okay, you may load it".

How can I intercept the loading process, so that I can inspect it on the fly and pass on the data bytes if they are allowed?

Hope you understand my question, thanks :-)

Example of how I do it right now:

function shall_be_blocked(info){
  var xhr = new XMLHttpRequest();
  xhr.open("GET", file, false);
  //... #load the file and inspect the bytes
  if (xhr.responseText=="block it") {
     return true;
  }
  return false;
}

chrome.webRequest.onBeforeRequest.addListener(
  function(info) {
    ret = shall_be_blocked(info);
    if (ret ...){return {cancel:true};}//loads the file once, as it is getting blocked
    return {};//loads the file twice
  },
  {},["blocking"]
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...