using document.getElementsByTagName on a page with iFrames - elements inside the iframe are not being picked up

和自甴很熟 提交于 2019-12-01 20:53:48

That's because elements that are in iframes are not a part of the parent document.

To get anything inside an iframe, you need to access the iframe's contentDocument. So, your code might look like this:

var IMGmatches = [], IMGelems = document.getElementsByTagName("img"),
    iframes = document.getElementsByTagName('iframe'), l = IMGelems.length,
    m = iframes.length, i, j;
for( i=0; i<l; i++) IMGmatches[i] = IMGelems[i];
for( j=0; j<m; j++) {
    IMGelems = iframes[j].contentDocument.getElementsByTagName("img");
    l = IMGelems.length;
    for( i=0; i<l; i++) IMGmatches.push(IMGelems[i]);
}

Here is a function that will return a set of all elements starting from(and including) a root, including iframes where possible (non CORS) and shadow dom:

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('*')) subtreeSet(child, theset);
	}
	return theset;
}

subtreeSet(document).forEach(elem => { 
  if (elem.style) elem.style.backgroundColor='yellow'; 
});
<div>TOP</div><br>
<div>IFRAME<br><iframe></iframe></div>

Tested only in Chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!