Search code examples
javascriptnode.jsbuttonclickparent-child

In a parent window, how do I know which button is clicked in a child window?


In JS ...

In a parent window, how do I know which (or if a) button is clicked in a child window?

I have a node function which builds the HTML page and creates the buttons as such:

    tosend += "</pre> <center>  <button id='abort' onclick='window.close() '>Cancel/Abort</button> " +
              "<button id='acceptid' type='button' " + "onclick='window.close();'>Accept & Close</button> </center> </body> </html>";

Node sends the HTML back to the parent client which creates the child and waits for the user response like so:

ws.onmessage = function(e) {
    const w = window.open('about:blank');
    w.document.open();
    w.document.write(e.data);
    w.document.close();

    /* wait for user to confirm */
    const timer = setInterval(() => {
        tosend = "";

        if (w.document.getElementById("acceptid").clicked == true) {    /* placeholder, see note below */
            tosend = "acceptid button clicked";
        } else {
            tosend = "none";
        }

        if (w.closed) {
            clearInterval(timer);

            ...
            ...

        }
    }, 500);
}

Note - I realize that ".clicked" is not valid. It's just there as a placeholder.


Solution

  • I got this working by changing:

    tosend += "</pre> <center>  <button id='abort' onclick='window.close() '>Cancel/Abort</button> " +
      "<button id='acceptid' type='button' " + "onclick='window.close();'>Accept & Close</button> </center> </body> </html>";
    

    to

    tosend += "</pre> <center>  <button id='abort' onclick='window.close();'>Cancel/Abort</button> " +
      "<button id='acceptid' type='button' " +
      "onclick='window.opener.setValue(true);window.close();'>Accept & Close</button> </center> </body> </html>";
    

    In the client parent I added:

    var usedconfirm;
    
    function setValue(val1) {
      usedconfirm = 1;
    }
    

    Just before the timer in the parent client added:

    usedconfirm = 0;
    

    And replaced:

    if (w.document.getElementById("acceptid").clicked == true) {
    

    with:

    if (usedconfirm) {