11

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.

Jed
  • 10,649
  • 19
  • 81
  • 125

1 Answers1

14

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>');
bobjoe
  • 673
  • 6
  • 11
  • I had to set `window.location.href = "#"` then it worked for me. I'm using TypeScript. – goflo Dec 27 '17 at 10:00
  • thanks this solution works nice! about:blank url has disappeared now i see my page link with hash at the end. – jmp Sep 03 '18 at 18:47
  • Thank you! Thank you! I've had the exact same problem for a couple of years and could not work out how to cure it. I wonder why this should work? But never mind. It does! Yippee – user1210923 Jan 06 '21 at 15:24