在我的应用程序中,我需要允许用户右键单击图像以将图像保存到磁盘。但是,我注意到使用我的特定代码,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/