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

Viewed 30

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.

2 Answers

You won't really need an interval for that. You could just attach a click event handler to the document and that should do it.

function onUserSelection(event) {
  let tosend = '';

  if (event.target.id === 'acceptid') {
    tosend = 'acceptid button clicked';
  } else if (event.target.id === 'abort') {
    tosend = 'none';
  }

  console.log(tosend);
}

ws.onmessage = function (e) {
  const w = window.open('about:blank');
  w.document.open();
  w.document.addEventListener('click', onUserSelection, { once: true });
  w.document.write(e.data);
  w.document.close();
};

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) {
Related