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

You can identify the relative place of the document in the hierarchy of iframes. Depending on the structure of the page, this can solve your problem.

Your extension is able to access window.parent and its frames. This should work, or at least works for me in a test case:

// 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.

I was itching to do it myself, so here you go:

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

Leave a Comment