显示任何WebPage的所有帧列表

时间:2015-07-20 07:12:49

标签: javascript loops iframe recursion frame

我想创建一个递归JavaScript循环,它可以显示所有(使用IFRAMES标记或使用FRAME标记)。结果应该给出FrameName,NestingLevel,FrameURL等。

例如,当我们在Google Chrome中打开“开发者工具”时,我们可以在控制台标签中看到所有框架(甚至是嵌套框架)。 Image showing list for Frames using GoogleChrome is shown here for the reference

请给出一个带有错误处理(iframe安全问题)的递归循环。!

示例代码

function getFramesInfo(oWin) {
  arrFrames = oWin.frames;
  //alert(arrFrames.length);
  if (arrFrames.length == 0) {
    alert('document do not have frame(s)');
  } else {
    for (i = 0; i < arrFrames.length; i++) {
      console.log(i + ' ' + arrFrames[i].location.href);
      if (arrFrames[i].document) {
        getFramesInfo(arrFrames[i]);
      }
    }
  }
}
//Calling This Function
getFramesInfo(window);

3 个答案:

答案 0 :(得分:0)

谷歌搜索和探索之后我找到了一个简单的解决方案,但我认为应该改进这个答案以避免任何可能的错误(应该进行精确的错误处理以避免跨域框架问题) :

示例解决方案

// first parameter is frame (window) in which to get sub frames
// second is the array to build on
function getAllFrames(frame, allFrameArray) {
  allFrameArray.push(frame.frames);
  for (var i = 0; i < frame.frames.length; i++) {
    getAllFrames(frame.frames[i], allFrameArray);
  }
  return allFrameArray;
}

<强>用法

var allFramesArray = getAllFrames(window, new Array());
console.log(allFramesArray.length); // number of frames in array
for (var i = 0; i < allFramesArray.length; i++) {
  try {
    console.log(allFramesArray[i].location.href); // location of first frame in array}
  } catch (e) {
    console.log('Error in Accessing Frame No.' + i); // location of first frame in array}
  }
}

答案 1 :(得分:0)

替代/改进代码

function getAllFrames(frame, allFrameArray) {
  allFrameArray.push(frame.frames);
  for (var i = 0; i < frame.frames.length; i++) {
    getAllFrames(frame.frames[i], allFrameArray);
  }
  return allFrameArray;
}
//Usage:

var allFramesArray = getAllFrames(window, new Array());
console.log(allFramesArray.length); // number of frames in array
for (var i = 0; i < allFramesArray.length; i++) {
  console.log('\n\n No.'+ (i+1) + '.');
  try {
    console.log(allFramesArray[i].id);
    console.log(allFramesArray[i].name);
    console.log(allFramesArray[i].location.href); // location of first frame in array}
  } catch (e) {
    console.log('Error in Accessing Frame No.' + (i+1) ); // location of first frame in array}
  }
}

答案 2 :(得分:0)

这是另一个(快捷示例)

  var i = new Array;

  function wow(a, n) {
    t = '';
    for (i[n] = 0; i[n] < a.length; i[n]++) {
      try {
        t += a[i[n]].name + ' \n';
      } catch (e) {
        t += 'Error \n';
      }
      if (a[i[n]].frames.length) t += wow(a[i[n]].frames, n + 1);

    }
    return t;
  }

  //Usage:
  console.log(wow(top.frames, 0));