MikeWyatt
MikeWyatt

Reputation: 7871

Attaching callback to popup window in IE 9

I'm creating a popup window and attaching a callback function to it. There is a button in the popup's page which calls this callback when clicked. This works in Firefox 4 and Chrome 10, but not IE 9. The "myPopupCallback" property that I add to the window is found and executed by Firefox and Chrome. In IE, it is undefined.

Is there something about IE that causes problems with attaching data or functions to a window?

Main window code

var popup = window.open(url, '', 'status=0,menubar=0,toolbar=0,resizable=1,scrollbars=1');
$(popup.document).ready(function()
{
    popup.myPopupCallback = function(rows)
    {
        // ...do stuff with rows...
    };
});

Popup window code

$('#btn-ok').click(
    function()
    {
        var rows = $('#rows');

        // IE 9 throws an error on the next line because window.myPopupCallback is undefined
        window.myPopupCallback(rows);
    });

Upvotes: 2

Views: 2078

Answers (1)

donut
donut

Reputation: 9507

window.open() is a non-blocking operation which means that before the new window has finished opening JavaScript will move on to next line of code. Because of this, setting a property may not "stick" if it's done too soon. I just ran into this problem myself.

Thanks to a lot of help from Erik I found the following seems to work pretty well.

var popup = window.open(
      url, '', 'status=0,menubar=0,toolbar=0,resizable=1,scrollbars=1'
);
$(popup.document).ready(function(){
   var setPopupPropertiesInterval = setInterval(
         function setPopupProperties() {
            popup.myPopupCallback = function(rows)
            {
               // ...do stuff with rows...
            };
            if (popup.closed || popup.myPopupCallback) {
               clearInterval(setPopupPropertiesInterval);
            }
         }, 1
   );
});

This will keep trying to add the function to the popup window until it is added or the popup window is closed.

In my extremely brief testing this worked across browsers but I'm not sure about the performance implications of such a fast interval and had no issues with performance. Note that most (all?) browsers will not actually run the code in 1 ms intervals, but something a bit higher, usually 10 ms. Chrome is an exception to this in that it tries to get close to 1 or 2ms.

On one Windows XP machine running IE 7 I ran into an issue where the browser would freeze upon launching the pop-up. The window would pop-up but nothing would load and the browser would become slow to respond. However, I have tested this on several other machines running Windows XP and IE 7 and was not able to reproduce the issue.

Upvotes: 3

Related Questions