有没有办法唯一标识内容脚本在我的 Chrome 扩展程序中运行的 iframe?

c00*_*0fd 4 javascript iframe google-chrome google-chrome-extension

在我的 Chrome 扩展程序中,我将内容脚本注入到IFRAMEs页面内的所有内容中。这是manifest.json文件的一部分:

"content_scripts": [
    {
        "run_at": "document_end",
        "all_frames" : true,
        "match_about_blank": true,
        "matches": ["http://*/*", "https://*/*"],
        "js": ["content.js"]
    }
],
Run Code Online (Sandbox Code Playgroud)

因此,具有多个的单个网页IFRAMEs最终将运行我注入的content.js.

内部的逻辑content.jsIFRAME它注入的每个页面或从主/首页收集数据,并将其发送回后台脚本(使用chrome.runtime.sendMessage.)。后台脚本反过来需要将数据存储在全局变量中,稍后使用在扩展本身。

我面临的问题是应用程序需要区分从多个接收到的“数据” IFRAMEs,因为我的数据收集方法可以在用户与页面交互时重复调用,因此我不能简单地“转储”接收到的数据将后台脚本转换为数组。相反,我需要使用dictionary-type 数据存储。

我可以IFRAME通过运行以下命令来判断数据是来自首页还是来自首页:

//From the `content.js`
var isIframe = window != window.top;
Run Code Online (Sandbox Code Playgroud)

我的想法是,如果我收集每个页面的 URL,IFRAME那么我应该能够将其用作唯一键,将数据存储在我的字典类型全局变量中:

//Again from content.js
var strUniqueIFrameURL = document.URL;
Run Code Online (Sandbox Code Playgroud)

好吧,那是行不通的,因为两个或多个IFRAMEs可以具有相同的 URL。

所以我最初的问题是——如何IFRAMEs在页面上区分?Chrome 是否为他们分配了一些唯一的 ID 或某些东西?

Xan*_*Xan 6

您可以确定文档在 iframe 层次结构中的相对位置。根据页面的结构,这可以解决您的问题。

您的扩展程序能够访问window.parent其框架。这应该有效,或者至少在测试用例中对我有效:

// Returns the index of the iframe in the parent document,
//  or -1 if we are the topmost document
function iframeIndex(win) {
  win = win || window; // Assume self by default
  if (win.parent != win) {
    for (var i = 0; i < win.parent.frames.length; i++) {
      if (win.parent.frames[i] == win) { return i; }
    }
    throw Error("In a frame, but could not find myself");
  } else {
    return -1;
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以修改它以支持嵌套 iframe,但原则应该有效。

我很想自己做,所以你去吧:

// Returns a unique index in iframe hierarchy, or empty string if topmost
function iframeFullIndex(win) {
   win = win || window; // Assume self by default
   if (iframeIndex(win) < 0) {
     return "";
   } else {
     return iframeFullIndex(win.parent) + "." + iframeIndex(win);
   }
}
Run Code Online (Sandbox Code Playgroud)