getElementsByTagName递归地在具有iFrames的页面上



尝试使用使用文档时提供的有用代码。getElementsByTagName在一个带有iframe的页面上- iframe中的元素没有被拾取,但两个示例似乎都在查看第一"级别"。

尝试:

const subtreeSet = (root, theset) => {
if (!theset) theset=new Set();
if (!root || theset.has(root)) return theset;
theset.add(root);
if (root.shadowRoot) {
Array.from(root.shadowRoot.children).forEach(child => subtreeSet(child, theset));
} else {
if (root.tagName === 'IFRAME') { try { root=root.contentDocument.body; theset.add(root); } catch (err) { root=null; /* CORS */ } }
if (root && root.getElementsByTagName) for (const child of root.getElementsByTagName('a')) subtreeSet(child, theset);
}
return theset;
}
console.log(subtreeSet(document));

期望看到所有的链接,但是只看到了不在嵌套iframe内的链接。

iframe在HTML中是一个有点特殊的标签。要访问此标签,您有2个选项contentWindowcontentDocument。你有这个链接中的信息堆栈溢出问题。

之后,您可以查看其他链接以了解如何组合这两个属性。代码应该是这样的:

var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var innerTag = innerDoc.getElementsByTagName('a');

请记住,在你的代码中,你正在做root.contentDocument.body,这个.body是不正确的。

最新更新