1.代码及问题
vue代码
<template>
<iframe
id="iframe"
frameborder="0"
allowtransparency="true"
></iframe>
</template>
js代码
mounted() {
const iframe = document.getElementById("iframe").contentDocument ||
document.frames["iframe"].document
const iframeBody = iframe.body
iframeBody.innerHTML = '<p>iframe部分内容</p>'
}
问题:chrome浏览器运行正常,firefox中,iframe内容不展示
2.解决问题
F12检查发现,firefox中,iframe的src属性为about:blank,将此属性设置为 javascript: 或者 about: 则火狐浏览器展示正常,而此时chrome中iframe不展示,因此,需要判断,如果是火狐浏览器,将iframe的src属性设置为 javascript: 或者 about: 即可解决
代码:
<template>
<iframe
id="iframe"
frameborder="0"
allowtransparency="true"
:src="iframeSrc"
></iframe>
</template>
data() {
return {
iframeSrc: navigator.userAgent.match("Firefox") ? 'javascript:' : ''
}
}
本文探讨了在Chrome和Firefox浏览器中,使用Vue进行动态iframe内容设置时遇到的问题。在Chrome中正常,但Firefox下iframe内容无法显示。原因是Firefox要求iframe有src属性。解决方法是通过检测浏览器类型,当检测到Firefox时,设置iframe的src为'javascript:'或'about:',从而确保在两种浏览器下都能正确显示内容。

1481

被折叠的 条评论
为什么被折叠?



