google-chrome - "Save image as.."使用 window.open() 和 document.write() 时无法在 Google Chrome 中工作

标签 google-chrome window.open document.write save-image

在我的应用程序中,我需要允许用户右键单击图像以将图像保存到磁盘。但是,我注意到使用我的特定代码,Google Chrome 是唯一不允许用户“将图像另存为...”的浏览器,除非用户首先选择 Open image in new tab然后,从那里选择 Save image as.. .

由于所有其他主要浏览器(包括 Mobile Chrome)都按预期工作,我不确定我是否没有以标准/正确的方式实现我的代码,或者问题是否出在 Chrome 上。

示例:

以下 HTML 是我正在做的精简版。它将允许您单击一个按钮以打开一个包含图像的新窗口。

要测试/确认我上面描述的问题,请右键单击图像并选择 Save image as.. - 你应该注意到什么都没有发生。但是,如果您右键单击图像并选择 Open image in new tab ,您将可以Save image as..从那里。

<html>
<head>
    <title></title>
    <script>
        function foo() {
            var tab = window.open();
            tab.document.write('<p>Right-click, then click "Save image as ..."</p><img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png" />');
        }
    </script>
</head>
<body>
    <button onclick="foo();">Open</button>
</body>
</html>

这是 Chrome 的问题还是有其他方法可以使用 window.open()连同 document.write()让 Chrome 像其他浏览器一样工作(即不必首先选择 Open image in new tab

最佳答案

我找到了一个似乎有效的解决方案。使选项卡具有位置属性。我不确定为什么需要这样做,但它在 Chrome 48 上对我有用。

document.write('<html>
<head>
    <title></title>
    <script>
        function foo() {
            var tab = window.open();
            tab.document.write('<p>Right-click, then click "Save image as ..."</p><img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png" />');
            tab.document.location = "#";
        }
    </script>
</head>
<body>
    <button onclick="foo();">Open</button>
</body>
</html>');

关于google-chrome - "Save image as.."使用 window.open() 和 document.write() 时无法在 Google Chrome 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40644087/

相关文章:

javascript - 如何故意卡住 chrome 中的 javascript(插件/控制台)

javascript - 使用open.window()在新窗口中打开js程序

javascript - 为什么使用 document.write 在弹出窗口中插入的 HTML 页面需要刷新才能在 IE 7/8 中加载?

javascript - 使用 jQuery,是否可以在所有浏览器的新选项卡中打开文件?

javascript - 在 JavaScript 中,如何在没有 document.write() 的情况下创建动态版权日期?

css - 在固定容器内使用 CSS 最大高度过渡的 Chrome 滚动错误

javascript - Chrome 31.0 HTML5 Canvas 绘制图像

google-chrome - 403 错误仅在 chrome 中出现,在 FF 和 IE 中工作正常

javascript - document.write() 内联工作但不使用 jQuery 的 .html()

javascript - 为什么在 domready 上没有为 document.write(x) 显示字符串末尾的实体转义?