Ben Aston
Ben Aston

Reputation: 55779

Why does this throw an exception in IE 11

Why does the following code throw an 'Unspecified error' (on the appendChild line) in Internet Explorer 11 which I click the button?

<!DOCTYPE html>
<html>
<head>
    <script>
        function go() {
          var popUp = window.open('about:blank');
          popUp.document.body.appendChild(document.createElement('div'));
        }
    </script>
</head>
<body>
  <button onclick="go()">Click Me</button>
</body>
</html>

Upvotes: 1

Views: 1763

Answers (2)

imelgrat
imelgrat

Reputation: 2577

Popup blockers will typically only allow window.open if used during the processing of a user event (like a click). That might be causing the problem if you have popups blocked.

You need to call window.open from an event initiated by the user, e.g. clicking on a link, and that link needs to have target="_blank". Otherwise, Chrome and Firefox will block the popup.

Also, the error is triggered because popUp is not checked for null before attempting to append the div to it. If there's no popup, you can't append an element to it.

(I forgot this bit and Musa made me remember, so thanks) IE will block appending any element created in a different window context from the window context that the element is being appending to. So, instead of creating the DIV node using the current document, you need to create it using the popUp's context.

Summing it all up, this is how it would look the code.

<!DOCTYPE html>
<html>
<head>
        <script>
        function go() 
        {
            var popUp = window.open('about:blank');
            try 
            {
                // Make sure you have a body document when creating the new window....
                popUp.document.write("<html><head><title></title></head><body></body>");
                popUp.document.body.appendChild(popUp.document.createElement('div'));
            }
            catch(e)
            { 
                console.log(e);
            }
        }
        </script>
</head>
<body>
  <button onclick="go()">Click Me</button>
</body>
</html>

Upvotes: -1

Musa
Musa

Reputation: 97727

You're using the document of the current page to create the div, try using the document from the popup window

popUp.document.body.appendChild(popUp.document.createElement('div'));

Upvotes: 4

Related Questions