首页 > 解决方案 > javascript setAttribute iframe allowfullscreen 在 Chrome 中不起作用

问题描述

我在 iframe 中有一张地图(Chrome 67.0.3396.87)。例如

<iframe height="480px" 
src="http://brunob.github.io/leaflet.fullscreen/" 
width="450px">
</iframe>

我们使用的 CMS 会allowfullscreen从 iframe 中删除属性,因此我尝试使用 Javascript 将它们重新注入。

document.getElementsByTagName("iframe")[0].getAttribute("src") == "http://brunob.github.io/leaflet.fullscreen/" ? document.getElementsByTagName("iframe")[0].setAttribute("allowFullScreen", ""):null;

这会更改 DOM,但全屏按钮不起作用。但是,如果您从 iframe 开始并allowfullscreen设置,那么它确实有效。

<iframe height="480px" 
src="http://brunob.github.io/leaflet.fullscreen/" 
width="450px" allowfullscreen>
</iframe>

如何让 DOM 中的更改注册,它应该是自动的?!

标签: javascriptgoogle-chromedomiframeleaflet

解决方案


这是Chrome的一项功能,在其他浏览器中不存在,您必须在 allowfullscreen 按钮启动之前更新 iframe 内容。您可以通过首先使用 iframe 加载 HTML,然后运行脚本来解决它:

<iframe height="480px" 
src="http://brunob.github.io/leaflet.fullscreen/" 
width="450px">
</iframe>

<script>
// add allowfullscreen attribute to the iframe
document.getElementsByTagName("iframe")[0].getAttribute("src") == "https://interact.bcs.org/tracer/1/BCS_point_map.html" ? document.getElementsByTagName("iframe")[0].setAttribute("allowFullScreen", true):null;

// refresh the iframe container
document.getElementsByTagName("iframe")[0].src = document.getElementsByTagName("iframe")[0].src
</script>

推荐阅读