在调用 window.location.asassigned 后,网页渲染在 chrome/firefox 之间的行为不

Webpage rendering act differently between chrome/firefox after calling window.location.assign

本文关键字:firefox 之间 chrome location window 调用 asassigned 网页      更新时间:2023-09-26

我有一个网页显示实时 mjpeg 视频流(作为"img"(和一个下载位图文件的链接(该视频流的最后保存快照(。

当我在Chrome中单击链接时,浏览器会下载bmp文件,并且视频流可以毫无问题地保持渲染。

当我在 FireFox 中执行相同的操作时,会弹出一个对话框提示"保存/打开"文件,并且实时视频停止在页面上呈现。 将显示一个空占位符而不是图像。

下面是一个小的 html 代码来演示这个问题:

<html>
<head>
<script>
    function DownloadFile(link) {
        window.location.assign(link);
    }
</script>
</head>
<body>
    <img align="center" src="http://148.61.151.202/mjpg/video.mjpg?camera=1" height="375" width="500">
    <div style="color: rgb(142, 217, 255);" 
        onclick="DownloadFile('http://www.mywrapper.com/downloadfile/plug-ins/circle.bmp');">
        Download
    </div>
</body>
</html>

如何启用下载位图文件并保持页面在 FF 和 Chrome 中正确呈现?

这是因为两个浏览器处理链接分配过程的方式不同。您可以使用 Firefox 中的隐藏iframe对链接分配进行沙盒处理,以解决此问题。见下文:

<html>
    <head>
        ...
    </head>
    <body>
        <img align="center" src="http://148.61.151.202/mjpg/video.mjpg?camera=1" height="375" width="500">
        <button id="download">
            Download
        </button>
        <iframe style="display:none" id="f"></iframe>
        <script type="text/javascript">
            function DownloadFile (link) {
                var f = document.getElementById("f");
                f.contentWindow.location.assign(link);
            }
            document.getElementById("download").addEventListener('click', function(){
                DownloadFile('http://www.mywrapper.com/downloadfile/plug-ins/circle.bmp');
            });
        </script>
    </body>
</html>

这实质上导致 FF 让主窗口继续其工作,并创建一个具有自己的windowiframe,由 iframeElement.contentWindow 引用并遵循那里的链接分配。

iframe被用css隐藏:)

我在您的代码中所做的一些更改:

  1. 始终将脚本标签放在结束正文标签之前。这确保了 DOM 正确加载并且我们可以对其进行处理。此外,脚本加载会阻塞,这会减慢页面加载速度。把它们放在最后可以解决这个问题。
  2. 不要使用内联事件侦听器(即onclick=blabla(。查找、学习、练习和使用addEventListener
  3. 遵循正确的语义,使用 button 代替button。带有onclickdiv根本没有意义。