我正在尝试访问插入的 iframe 的window
对象。当我在检查中检查window.frames
时,它是基本窗口的窗口对象,而不是 iframe 的对象,window.frames.length
为 1。如何访问 iframe 的窗口对象?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<script src="script.js" defer></script>
</head>
<body>
some contents
<iframe src="iframe.html"></iframe>
</body>
</html>
是的,那个令人困惑...
根据规范,它返回window
对象,就像self
或globalThis
一样,这显然是Netscape的遗物。参考文献
对您来说重要的是,这个window
对象有一个.length
属性,说明有多少个子帧,然后您可以使用数字索引访问这些子帧的窗口。
例如,window[0]
应该返回 iframe 的窗口,但在 StackSnippet 的 null 来源的 iframe 中,它只会抛出一个错误。
console.log(window[0]);
some contents
<iframe src="iframe.html"></iframe>