I tried to open and close a popup in a simple HTML page with javascript, but maybe im missing basic knowledge of JS. First I tried to declare global variable myPopupHandle.
But hat is’nt populated in myOpenWnd. Here is the code maybe somebody can help.
<head>
<meta charset="utf-8">
<title>WndCloseTest</title>
</head>
<body>
<button type="button" onclick="myOpenWnd()">Open Popup Window</button>
<button type="button" onclick="myCloseWnd()">Close Popup Window</button>
<script type='text/javascript'>
let myPopUpHandle = null; // Always null
window.addEventListener("onunload", function(e) {
myCloseWnd();
});
function myCloseWnd() {
if (windowObjectReference != null)
windowObjectReference.close();
}
function myOpenWnd() {
const windowFeatures = "left=100,top=100,width=320,height=320";
/*
myPopUpHandle = window.open(
"https://www.mozilla.org/",
"mozillaWindow",
windowFeatures,
);
Don't work popUpHandle is null after this
*/
const handle = window.open(
"https://www.mozilla.org/",
"mozillaWindow",
windowFeatures,
);
if (!handle) {
console.log("his is likely caused by built-in popup blockers"); // logs the className of my_element
// The window wasn't allowed to open
// This is likely caused by built-in popup blockers.
// …
} else
window['windowObjectReference'] = handle;
}
</script>
</body>
2
Answers
Check that your browser does not block popup as your comment says.
As the popup window and the parent window are from different origin, you can’t directly close the popup window programmatically due to the same-origin policy, which restricts interactions between scripts from different origins for security reasons.
Read the docs at MDN
If the website from a different domain allows being embedded within an iframe and doesn’t have any security restrictions preventing it, you can indeed open it within an iframe in a popup window and close it programmatically from parent window.
https://jsfiddle.net/shardulvikrm/Lhq59ov4/