Set a callback function to a new window in javascript

后端 未结 2 1126
广开言路
广开言路 2020-11-27 05:38

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 t

相关标签:
2条回答
  • 2020-11-27 06:25

    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.

    0 讨论(0)
  • 2020-11-27 06:28
    var newWindow = window.open(window.location.origin);
    
    newWindow.onload = function() {
        $(newWindow.document.body).addClass('new-window-body-class');
    };
    
    0 讨论(0)
提交回复
热议问题