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.
1 2 3 4 |
var popUp = window.open('about:blank'); popUp.document.body.appendChild(document.createElement('div')); |
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
1 2 3 4 |
var popUp = window.open('about:blank'); popUp.document.body.appendChild(popUp.document.createElement('div')); |
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’).
HTML
1 2 3 4 |
<p id="clicker"><strong>Click me</strong></p> <div class="console"></div> |
Jquery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<script> $(function() { $('#clicker').click(function(){ var popUp = window.open('about:blank'); // Catch any exceptions and log them to the console, for debugging purposes try { // Make sure you have a body document when creating the new window.... popUp.document.write("Here I pop!"); popUp.document.body.appendChild(popUp.document.createElement('div')); } catch (e) { $('console').log(e); } }); }); </script> |
Source:https://imelgrat.me/javascript/popups-add-content-javascript/