5

When I run this code from a server, it works just fine, but it doesn't work in a Stack Snippet:

var wind;

function openWindow() {
  wind = window.open("https://www.google.com/", "wind", "width=1000,height=700");
}

function closeWindow() {
  wind.close();
}
<input type="button" onclick="openWindow()" value='Open'/>
<input type="button" onclick="closeWindow()" value='Close'/>

I have configured my browser to allow popups by default.

The log that is generated after trying to open a popup in a snippet is:

js:17 Blocked opening 'https://www.google.com/' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.

Why is window.open() blocked in snippets? I am sure there must be a good reason for doing so.

0

2 Answers 2

15

Security.

The moment you allow a window from a different domain to open, it gets access to the parent window and details about the parent page and can change the parent page.

4
  • Can't you just use noopener like you did here?
    – NobodyNada
    Commented Nov 15, 2016 at 16:38
  • These are not links, but an embedded IFrame. Different beasts.
    – Oded StaffMod
    Commented Nov 15, 2016 at 16:40
  • Oh yeah; sorry!
    – NobodyNada
    Commented Nov 15, 2016 at 16:40
  • 1
    I'm not sure if this answer is correct. If you attempt to access window.opener from a page on another (unsafe) domain, you'll get Error: Blocked a frame with origin "example.com" from accessing a cross-origin frame.. If you attempt to access it from a page on the (safe) same domain, there's nothing to worry about, especially since the Stack Snippet domain doesn't have access to anything sensitive anyway Commented Dec 22, 2019 at 10:11
0

Interesting. Nonetheless something very legitimate like this won't work either

$(document).ready(function() {
  $(":button").click(function() {
    html2canvas($("#testdiv"), {
      onrendered: function(canvas) {
        var myImage = canvas.toDataURL("image/png");
        var win = window.open(myImage);
        if (win) {
          //Browser has allowed it to be opened
          win.focus();
        } else {
          //Browser has blocked it
          alert('Please allow popups for this website');
        }
      }
    });
  });
});
div {
  width: 150px;
  background-color: #2C7CC3;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testdiv">
  This is an image
</div>
<button type="button">Click Me!</button>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .