Questions about internal and external access of iframe

1. Problem description

When designing a program, the front-end page structure has multiple iframes, and '#document' is used inside the iframe to load the internal pages, problems will arise in the internal and external access of the iframe due to this '#document':
① Elements inside #document cannot be selected from outside the iframe;
② Elements inside #document cannot be selected from outside the iframe (because #document is separated).

2. Solution

1. Select elements inside #document outside the iframe:

A document with a structure like this (for elements inside #document):

<iframe>
	#document
		<html>
		</html>
</iframe>
<iframe>
	#document
		<html>
		</html>
</iframe>
<iframe>
	#document
		<html>
		</html>
</iframe>

Assuming that the current selector top is an element outside the iframe, you can use:

top.getListiframe()[num].contentWindow.document.find('html');

At this time, what this selector selects is the html inside a #document.

2. Select from inside #document to outside iframe (to be resolved)

If it is already inside the #document, it is inside the iframe. At this time, it can be done as described in many solutions:

在 iframe 内部使用 window.parent 来访问包含它的父级窗口;
使用 window.top 来访问整个窗口层次结构的最顶层窗口。

This can solve the problem, but when a #document is wrapped outside, the structure becomes like this:

<iframe>
	#document
		<html>
			<div>
			</div>
		</html>
</iframe>

At this time, there is no way to use this window.parent in HTML (it will return undefined).

Guess you like

Origin blog.csdn.net/weixin_47278656/article/details/129896831