如何阻止iframe内的页面触发重定向跳转?
阻止iframe内部重定向跳转的解决方案
- 方案1:使用sandbox属性(推荐,跨域场景可用)
sandbox是HTML5提供的iframe安全限制属性,默认状态下会禁用所有风险行为,包括内部页面触发的重定向、弹窗、父级页面跳转等,你只需按需开放必要功能的权限即可。
针对你提供的YouTube嵌入示例,可修改为如下写法:
<iframe src="https://www.youtube.com/embed/DmiMpABb804" width="50%" height="50%" sandbox="allow-scripts allow-same-origin allow-presentation allow-media-storage-access" > </iframe>
注意不要在sandbox的值中加入allow-top-navigation、allow-top-navigation-by-user-activation、allow-popups这类和跳转相关的权限,即可阻止所有iframe内触发的重定向行为。
- 方案2:同域iframe的JS拦截方案
如果你嵌入的是同域名下的iframe资源,可以通过JS监听导航事件实现更精细的跳转拦截:
const iframe = document.querySelector('iframe'); iframe.contentWindow.onbeforeunload = function(e) { // 拦截所有跳转行为 e.preventDefault(); return false; }; // 也可以监听iframe内部的a标签点击事件做定向拦截 iframe.contentDocument.addEventListener('click', function(e) { if (e.target.tagName === 'A' && e.target.getAttribute('href')) { e.preventDefault(); } });
注:该方案仅适用于同域iframe,跨域场景下浏览器会限制对iframe内部DOM和window对象的访问,无法生效。
内容的提问来源于stack exchange,提问作者Abu Naaim Md. Montasir Rahman
相关产品推荐
相关产品推荐

