防止iframe连接重定向到父级页面

原文:https://www.douban.com/note/586337871/


iframe页面的链接是可以让父级页面重定向的,如:


页面A

<body>
<h1>hello</h1>
<iframe src='b.html'></iframe>
</body>


页面B


<body>
<h1>hi</h1>
<a href="http://www.baidu.com" target="_top">
</body>

在这种情况下,当我们在页面A中点击iframe页面B的链接,就会让整个页面的请求链接改变

iframe中的sandbox属性可设置iframe页面中的链接不重定向到父级页面

在PC端:

<iframe src="b.html" sandbox="allow-forms allow-scripts allow-same-origin allow-popups">
</iframe>


在移动端:

<iframe src="b.html" sandbox="allow-forms allow-scripts allow-same-origin">
</iframe>



在HTML中,如果想要在一个嵌套在`<iframe>`标签内的页面内部刷新其页面,由于浏览器的安全限制(同源策略),直接操作窗口是不可能的,因为JavaScript无法跨域访问。但是,你可以利用一些技巧间接达到这个目的: 1. **通过postMessage** API**:** 如果页面已经设置了`window.postMessage()`监听,那么子页可以发送一个自定义事件到页面页面接收到后触发刷新。示例: ```javascript window.parent.postMessage('refreshParent', '*'); ``` 页面监听并处理消息: ```javascript window.addEventListener('message', function(event) { if (event.data === 'refreshParent') { location.reload(); } }); ``` 2. **利用location.hash变化**: 子页面可以改变自身的`#hash`值,然后页面通过监听`hashchange`事件来刷新自身。这不会触发完整的页面加载,仅刷新当前文档的部分内容。 3. **页面提供一个URL查询参数**: 子页面在`location.search`中添加特定的查询字符串,然后页面根据查询参数判断是否需要刷新。例如: 子页: ```html <a href="parent.html?refresh=true">刷新页面</a> ``` 页: ```javascript var shouldRefresh = new URLSearchParams(window.location.search).get('refresh'); if (shouldRefresh === 'true') { location.reload(); } ``` 需要注意的是,以上方法都需要页面能够接受来自子页面的操作,并且通常用于特定的应用场景,而非一般网页设计的标准做法。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值