Parent and child browser windows can communicate when they share the same origin. Modern browsers may block popups unless window.open() is called directly from a user action.
let childWindow = null;
$( "#open-child" ).on(
"click",
function () {
childWindow = window.open(
"window-child-open-close.php",
"plus2netChild",
"width=600,height=500"
);
}
);
$( "#close-child" ).on(
"click",
function () {
if (
childWindow &&
!childWindow.closed
) {
childWindow.close();
}
}
);
Demo: open and close child window →
if (
window.opener &&
!window.opener.closed
) {
const parentValue =
window.opener
.document
.querySelector( "#t1" )
.value;
}
Demo: exchange data between parent and child →
childWindow.addEventListener(
"beforeunload",
function () {
refreshParentData();
}
);
Direct DOM access requires the same origin. For more loosely coupled window communication, use postMessage().
// Parent
window.addEventListener(
"message",
function ( event ) {
if (
event.origin !==
window.location.origin
) {
return;
}
$( "#t1" ).val(
event.data.value
);
}
);
// Child
window.opener.postMessage(
{
value:
$( "#t2" ).val()
},
window.location.origin
);
Demo: refresh parent after child action →
Demo: reload part of parent content →
<script>
$(document).ready(function() {
//////////////var newWin; // declaring global variable
////////////////////////////
$("#b_open").click(function(){
newWin = window.open("window-child-open-close.php");
})
//////////////
$("#b_close").click(function(){
newWin.close();
})
///////
})
</script><script>
$(document).ready(function() {
//////////////
$("#b2").click(function(){
self.close();
})
///////
})
</script><script>
$(document).ready(function() {
////////////////
var str=parent.window.opener.$('#t1').val()
$('#d1').html("Parent Window Data = " + str);
//////////////
$("#b2").click(function(){
var sel=$('#t2').val();
window.opener.$('#t1').val(sel);
self.close();
})
///////
})
</script>$("#b_open").click(function(){
newWin = window.open("window-child-reload.php");
newWin.onunload = my_load;
})function my_load(){
if(newWin.location != "about:blank"){ // Don't do any thing if child window is open
var str=$('#t1').val();
str=parseInt(str)+1;
$("#t1").attr('value',str);
}
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.