Set a callback function to a new window in javascript

旧城冷巷雨未停 提交于 2019-11-26 08:18:46

问题


Is there an easy way to set a \"callback\" function to a new window that is opened in javascript? I\'d like to run a function of the parent from the new window, but I want the parent to be able to set the name of this particular function (so it shouldn\'t be hardcoded in the new windows page).

For example in the parent I have:

function DoSomething { alert(\'Something\'); }
...
<input type=\"button\" onClick=\"OpenNewWindow(linktonewwindow,DoSomething);\" />

And in the child window I want to:

<input type=\"button\" onClick=\"RunCallbackFunction();\" />

The question is how to create this OpenNewWindow and RunCallbackFunction functions. I though about sending the function\'s name as a query parameter to the new window (where the server side script generates the appropriate function calls in the generated child\'s HTML), which works, but I was thinking whether there is another, or better way to accomplish this, maybe something that doesn\'t even require server side tinkering.

Pure javascript, server side solutions and jQuery (or other frameworks) are all welcomed.


回答1:


Updated for comments: If you're opening your window via window.open() then in your child page you can set a function in the child to just be a reference pointing to a parent function, so have this in the child page:

var RunCallbackFunction = function() { }; //reference holder only

Then in your parent (opener), set that function when that child window loads, like this:

//random function you want to call
function myFunc() { alert("I'm a function in the parent window"); }

//to actually open the window..
var win = window.open("window.html");
win.onload = function() { win.RunCallbackFunction = myFunc; };

This assigns the function in your parent to now be the target of that child...and you can point each child to a different function if you wish, they're all independent.




回答2:


var newWindow = window.open(window.location.origin);

newWindow.onload = function() {
    $(newWindow.document.body).addClass('new-window-body-class');
};


来源:https://stackoverflow.com/questions/2797560/set-a-callback-function-to-a-new-window-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!