通过Chrome扩展搜索页面内的javascript

Searching for for javascript within page via Chrome extension

本文关键字:javascript Chrome 扩展 搜索 通过      更新时间:2023-09-26

我想建立一个简单的Chrome扩展,可以搜索当前活动选项卡的HTML/DOM,并在弹出窗口中打印出包含与某个源匹配的javascript的元素数量。

我在Chrome扩展指南中读到,内容脚本无法与页面上的其他javascript交互,甚至无法看到其他javascript,这让我相信这是不可能的。有人知道创建这种类型的扩展是否可行吗?

不久前我也做过类似的事情;我需要查看元素的onclick和其他属性,这通常是不可能的:

值得注意的是,由页面和扩展共享的JavaScript对象会发生什么——例如,window.onload事件。每个孤立的世界看到的都是它自己版本的对象。

有一种将代码注入页面上下文的技术。这样的代码可以到达窗口的JS上下文,然后将其传递给内容脚本。在我的情况下,我只是添加了一个额外的属性与JS附加节点。

// 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) 
  });
});

请注意,对于实际的<script>标签,您可以自由地检查srctextContent属性。