简体   繁体   中英

Searching for for javascript within page via Chrome extension

I wanted to build a simple Chrome extension that would search the HTML/DOM of the current active tab and print out in a popup the number of elements that contained javascript matching a certain source.

I read in the Chrome extension guides that the Content Scripts are unable to either interact with or even see other javascript on the page, leading me to believe this is not possible. Does anyone know for sure if creating this type of extension is feasible?

I did something similar not long ago; I needed to see elements' onclick and other attributes, which is not normally possible:

It's worth noting what happens with JavaScript objects that are shared by the page and the extension - for example, the window.onload event. Each isolated world sees its own version of the object.

There is a technique of injecting code into the page's context . Such code can reach the window's JS context and then pass it to your content script. In my case, I just added an extra attribute to nodes with JS attached.

// Fill inline handler copies
function fillClickHandlers(callback) {
  var injected = function() {
    // Note: This executes in another context!
    // Note: This assumes jQuery in the other context!
    $("[onclick]").each(function() {
      this.dataset["onclick"] = this.attributes["onclick"].value;
    });
    $("[onsubmit]").each(function() {
      this.dataset["onsubmit"] = this.attributes["onsubmit"].value;
    });
    $("[onload]").each(function() {
      this.dataset["onload"] = this.attributes["onload"].value;
    });
  }

  var s = document.createElement('script');
  s.textContent = "(" + injected + ")();";
  (document.head||document.documentElement).appendChild(s);
  // Script is synchronously executed here
  s.parentNode.removeChild(s);
  callback();
}

// Erase inline handlers copies
function eraseClickHandlers(callback) {
  $("[data-onclick], [data-onsubmit], [data-onload]").each(function() {
    delete this.dataset.onclick;
    delete this.dataset.onsubmit;
    delete this.dataset.onload;
  });
  callback();
}

// Usage:
fillClickHandlers(function() {
  doActualWork(function() {
    eraseClickHandlers(doSomethingElse) 
  });
});

Note that for actual <script> tags, you can freely inspect src or textContent attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM