Passing Variable from child popup window to parent popup window

4k views Asked by At

I have PopUp window which goes to upload.jsp, which upload the file to directory.

The uploading logic is written in upload.jsp. My problem is I wanted get the saved path to parent popup window textfield.

1

There are 1 answers

1
T.J. Crowder On BEST ANSWER

The child window has a property, opener, which refers to the window that opened it. Provided they're both from the same origin, the child can access global variables on the parent like this:

opener.globalVariable

That means it can access the parent window's document as opener.document, and so can use opener.document.getElementById or opener.document.querySelector to get at elements in the parent window.

Example:

Parent page:

<!doctype html>
<html lang="en">
<body>
<input type="text"><input type="button" value="Click me">
<script>
document.querySelector("input[type=text]").value = Math.floor(Math.random() * 10000);
document.querySelector("input[type=button]").addEventListener(
  "click",
  function() {
    var wnd = window.open("popup.html");
  },
  false
);
</script>
</body>
</html>

Popup page:

<!doctype html>
<html>
<body>
<script>
var field;
if (!opener) {
    display("Not opened as a popup");
} else {
    field = opener.document.querySelector("input[type=text]");
    display("Value is " + field.value);
}

function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = msg;
    document.body.appendChild(p);
}
</script>
</body>
</html>