Skip to content

现代JavaScript教程笔记——frame and windows

检查网页是否在iframe中

javascript
if (window.self === window.top) {
  console.log('当前页面在iframe中');
} else {
  console.log('当前页面不在iframe中');
}

sandbox属性

这个属性可以控制iframe中的内容的行为。

通过设置这个属性的具体值,可以放开对iframe中的内容的行为限制。

html
<iframe src="https://www.google.com" sandbox="allow-scripts allow-same-origin"></iframe>

包括以下可配置项

  • allow-same-origin:允许将iframe视为同源页面。
  • allow-top-navigation:允许iframe修改parent.location。
  • allow-forms:允许iframe内容提交表单。
  • allow-scripts:允许运行来自iframe内容的脚本。
  • allow-popups:允许iframe内容创建新的弹窗。

使用postMessage进行跨域通信

postMessage是window对象的一个方法,可以用于在不同的窗口之间传递消息。

javascript
// 发送消息
window.parent.postMessage('Hello from iframe', 'https://example.com');

// 接收消息
window.addEventListener('message', (event) => {
  console.log(event.data);
});

当然,这个方法也可以用来和iframe进行通信。