Popups can be useful

Let’s face it. Popups are not a nice browser feature and they can be very annoying. But, in some situations, they can be useful and it’s important to know how to work with them. Especially when content in popups is generated / managed using JavaScript.

One of the things to know is that most popup blockers will not allow opening popups unless function window.open if called during the processing of a user event (like a click). Basically, that means calling window.open during page load or using some non-user-initiated interaction will not work as the new window will be blocked.

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

As we all know, Internet Explorer always comes with its little quirks and popups are no exception. IE doesn’t allow appending cross-window elements. In other words, if you create an element in a pop-up, you can’t append it to the opener’s document. Always create elements to append in the same document they’re going to be appended.

Also, even when creating a popup in response to a user-event, IE will stop JavaScript from appending any element created in a different window context from the window context that the element is being appending to. So if you try to execute the following, IE will throw a SCRIPT5022 exception. This feature seems not be documented at MSDN though.



Avoid browser exceptions

The solution is quite simple. Instead of creating the DIV node using the current document’s context, you need to create it using the popUp’s context. The code will change a bit and look like this

Also, some browsers don’t add the boilerplate code to the DOM (<html>, <head>, <title>, <body>) so you need to make sure you have those elements before attempting to append child elements to them.

Summing it all up, this is how it would look the code to create popup append a child DIV element to it (when clicking on an element with ID ‘clicker’).

See the Pen NvzEPV by Iván Melgrati (@imelgrat) on CodePen.dark

I told you popup can be very annoying, didn’t I?

Summary
Adding content to popups using JavaScript
Article Name
Adding content to popups using JavaScript
Description
In some situations, popups can be useful and it's important to know how to work with them. Especially when content in popups is generated / managed using JavaScript.
Author
Publisher Name
Iván Melgrati
Publisher Logo