为何动态给iframe添加滚动条伪类会导致浏览器崩溃?
动态注入外部CSS到iframe导致浏览器崩溃问题
崩溃复现步骤
- 在主页面HTML中添加iframe:
<iframe id="iframe-box" onload="onloadcss(this)" src="..." style="width: 100%; border: none;"></iframe>
- 主页面中添加JS代码,用于iframe加载完成后注入外部样式:
function onloadcss(iframe) { const idoc = iframe.contentWindow.document; const styleLink = idoc.createElement("link"); styleLink.href = "/public-style.css"; styleLink.rel = "stylesheet"; idoc.head.appendChild(styleLink); }
- 外部CSS文件
public-style.css内容为:
::-webkit-scrollbar-thumb, ::-webkit-scrollbar, ::-webkit-scrollbar-track { display: none; }
- 打开浏览器控制台(F12),使用DOM选择器工具(快捷键
Ctrl+Shift+C)。 - 将鼠标悬停在该iframe上,浏览器必然崩溃。
可正常运行的替代方案
采用以下任意一种方式,均不会触发崩溃:
- 直接在iframe嵌套的
chicken-soup/index.html中添加内联样式。 - 直接在iframe嵌套的
chicken-soup/index.html中通过link标签引入外部CSS。 - 动态创建style标签并写入样式内容,再添加到iframe的head中(而非引入外部CSS文件)。
请问该崩溃问题的原因是什么?
内容的提问来源于stack exchange,提问作者Container
相关产品推荐
相关产品推荐

