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

2024-03-10

在我的 Chrome 扩展中,我注入了内容脚本进入所有IFRAMEs在一个页面内。这是其中的一部分manifest.json file:

"content_scripts": [
    {
        "run_at": "document_end",
        "all_frames" : true,
        "match_about_blank": true,
        "matches": ["http://*/*", "https://*/*"],
        "js": ["content.js"]
    }
],

所以一个网页有多个IFRAMEs最终将运行我注入的许多副本content.js.

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

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

我可以判断数据是否来自IFRAME或者从首页运行以下命令:

//From the `content.js`
var isIframe = window != window.top;

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

//Again from content.js
var strUniqueIFrameURL = document.URL;

嗯,这是行不通的,因为两个或更多IFRAMEs可以有相同的 URL。

因此,我最初的问题是——如何分辨IFRAMEs在页面上分开吗? Chrome 是否分配给它们一些唯一的 ID 或其他内容?


您可以识别文档在 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;
  }
}

You can modify this to support nesting iframes, but the principle should work.

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

// 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);
   }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法唯一地标识我的 Chrome 扩展程序运行内容脚本的 iframe? 的相关文章

随机推荐