有没有一种方法可以为我的Chrome扩展唯一标识内容脚本运行的iframe

Is there a way to uniquely identify an iframe that the content script runs in for my Chrome extension?

本文关键字:标识 唯一 扩展 脚本 iframe 运行 Chrome 我的 一种 方法 有没有      更新时间:2023-09-26

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

"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或从主页面/主页面收集数据,并将其发送回后台脚本(使用chrome.runtime.sendMessage。)背景脚本

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

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

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

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

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

您可以修改它以支持嵌套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);
   }
}

为了扩展@Xan的答案,下面是我获得IFRAME索引的方法,考虑到它可能嵌套在其他IFRAMEs中。我将使用正向iframe表示法,这意味着父IFRAME索引将首先给出,然后是子索引等。此外,为了防止与浮点数混淆,我将使用下划线作为分隔符,而不是点。

因此,为了回答我最初的问题,一旦我在页面中有了IFRAME索引,它就会在该页面中唯一地识别它(加上IFRAME的URL)

这是获取它的代码:

function iframeIndex(wnd)
{
    //RETURN:
    //      = "" for top window
    //      = IFrame zero-based index with nesting, example: "2", or "0_4"
    //      = "?" if error
    return _iframeIndex(wnd || window);     // Assume self by default
}
function _iframeIndex(wnd)
{
    var resInd = "";
    var wndTop = window.top;
    if(wnd == wndTop)
        return resInd;
    var wndPar = wnd.parent;
    if(wndPar != wndTop)
    {
        resInd = _iframeIndex(wndPar) + "_";
    }
    var frmsPar = wndPar.frames;
    for(var i = 0; i < frmsPar.length; i++)
    {
        if(frmsPar[i] == wnd)
            return resInd + i;
        }
    return resInd + "?";
}

每次加载内容脚本时,您都可以使用时间戳和随机数的组合生成伪唯一id,如下所示:

var psUid = (new Date()).getTime() + '_' + Math.random();

然后用这个ID将所有与数据相关的消息发送到后台。