Perry
Perry

Reputation: 139

pass javascript function to child window opened with window.open()

Having problems passing a javascript function from parent window to child window. Works fine in Firefox and Chrome but not in IE (tested with IE11). Ironically it works even in IE if F12 dev tools are opened. This is in the same domain so cross domain blocks should no be an issue. What I have tried:

// on the parent
var newWin = window.open('href', 'title', ''); 
newWin.myFunc = function() { alert('test'); };

// on the child (when calling this I get error: 'myFunc' is undefined)
myFunc();

I know I can go the other way around -- calling a function defined on the parent from the child:

// on the parent
function myFunc() {
    alert('test');
}

// from child
opener.myFunc();

But for reasons beyond the scope of this questions I need to be able to pass an anonymous function to the child which it must to be able to execute.

Upvotes: 1

Views: 2800

Answers (2)

Muhammad Faisal
Muhammad Faisal

Reputation: 1

I had the same problem so I used setTimout() function to fix an undefined function called error in the child window. I hope this will work in all

//Add this to the page loads on the child browser window.
browsers.
setTimeout(function(){
  window.opener.FunctionName(param1,param2);
},1000);

Upvotes: 0

Perry
Perry

Reputation: 139

After several hours of trying all kinds of things, I ended up with this solution:

// on parent
var newWin = window.open('href', 'title', ''); 
$(newWin.document).ready(function() {
    newWin.myFunc = function() {
        alert('test');
    };
});

// on the child
myFunc();

Again Chrome and Firefox seem to allow variable declarations on the child window immediately before the document is loaded so this workaround is not needed for them but this will work just as well.

Upvotes: 1

Related Questions