In my app I need to allow a user to right-click on an image to save the image to disk. However, I have noticed that with my particular code, Google Chrome is the only browser that doesn't allow the user to "Save image as.." unless the user first selects Open image in new tab
and then, from there, choose to Save image as..
.
Since all other major browsers (including Mobile Chrome) work as expected, I'm not sure if I'm not implementing my code in a standard/correct way or if the problem is with Chrome.
Example:
The following HTML is a stripped down version of what I am doing. It will allow you to click a button to open a new window which will contain an image.
To test/confirm the problem I described above, right-click the image and select Save image as..
- You should notice that nothing happens. However, if you right-click the image and select Open image in new tab
, you will be able to Save image as..
from there.
<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>
Is this a problem with Chrome or is there another way that I can use window.open()
along with document.write()
to get Chrome to work like other browsers (i.e. without having to, first, choose Open image in new tab
.
I found a solution that seems to work. Make the tab have a location attribute. I'm not sure why this is needed, but it works for me on 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>');