how to call function in parent window when closing child window - javascript

I have a parent window and a child window. I want to call a function when closing the child window .
The code of parent window is below:
function Button4_onclick(){
newWin=window.open("http://10.10.19.22:8086/childwindow.jsp");
newWin.onunload = updatet();
}
function updatet()
{
if(newWin.location != "about:blank"){
document.getElementById("SerialNumber24").value='2345';
}
But this code not work and the function is called when opening the child window instead. So which event listener can I use for closing ? Thx.

That is possible if you own the child window. You need to set event onbeforeunload on the child.
Working fiddle: https://jsfiddle.net/itgoldman/9mafwu2L/33/
window.foo = function foo() {
alert("hello i am parent")
}
function open_window() {
var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=600,height=200,top=" + (screen.height - 400) + ",left=" + (screen.width - 840));
if (!win) {
alert("window open was blocked");
return;
}
win.document.write(str);
win.window.parent = this;
}
var script = `
window.onbeforeunload = function(ev) {
window.parent.foo();
return;
}
`;
var str = '<scri' + 'pt>' + script + '</scr' + 'ipt><h1>close me</h1>'

Related

Closing a JavaScript window with an onclick event

We have to make a JavaScript that opens a new Window, and then you need to be able to close it again with a click inside the window.
But my code does not work, could someone please provide me an answer to how this is done best?
function swipe() {
var largeImage = document.getElementById('largeImage');
var url = largeImage.getAttribute('src');
var w = largeImage.naturalWidth;
var h = largeImage.naturalHeight;
window.open(url,"Image", "height="+ h +", width="+ w +", resizable=yes");
var myWindow = window.self;
myWindow.addEventListener("click", clickHandler);
var elementIsClicked = false;
function clickHandler(){
elementIsClicked = true
}
function isElementClicked (){
if(elementIsClicked){
newWindow.close();
}
}
setInterval(isElementClicked, 500);
}
A comment says that newWindow is not defined anywhere. I think you meant to use the myWindow object. myWindow.close() will work, since it closes the window.
If you want to execute this when this first loads, you should put this in a window.onload function or a self-invoking function. Also, for full compatibility within all browsers, you should omit the resizable=yes part, because that is supported in only IE.
Also, if you want to use jQuery, you can execute this method within an $(window).load() function.
You can utilize document.write()
window.onload = function() {
var largeImage = document.getElementById("largeImage");
// var url = largeImage.getAttribute('src');
var w = largeImage.naturalWidth;
var h = largeImage.naturalHeight;
// open blank `window`
var popup = window.open("", "Image"
, "height="+ h
+", width="+ w
+", resizable=yes");
// write `img` `outerHTML` to `popup` `window`
popup.document.write(largeImage.outerHTML);
window.onclick = function() {
// close `popup`
popup.document.write("<script>this.close()<\/script>");
// remove `onclick` handler
this.onclick = null;
}
}
plnkr http://plnkr.co/edit/0KUPw3UlEF0ONO1vDoOU?p=preview
var newWindow;
function windowOpener() {
var url = "http://stackoverflow.com/questions/36387144/closing-a-javascript-window-with-an-onclick-event";
newWindow = window.open(url, "Popup", "width=700,height=500");
var timer = setInterval(function() {
if (newWindow.closed) {
alert("window closed");
clearInterval(timer);
}
}, 250)
}
<button onclick="windowOpener();">Open a window</button>
Here is the code for opening and detecting whenever it closes.
Here is the sample code on codepen.io http://codepen.io/sujeetkrjaiswal/pen/vGebqy
The code is not runnig in the stackoverflow for some reason, try it on codepen.
Thank you all for your answers.
Here is the solution to my problem:
function swipe() {
var largeImage = document.getElementById('largeImage');
var url = largeImage.getAttribute('src');
var w = largeImage.naturalWidth;
var h = largeImage.naturalHeight;
var popup = window.open(url,"Image", "height="+ h +", width="+ w +", resizable=yes");
popup.document.write('<img src="women_running_small.jpg" id="largeImage" style="width:95% ;height:95%; object-fit:contain"/>');
popup.onclick = function() {
// close `popup`
popup.document.write("<script>this.close()<\/script>");
// remove `onclick` handler
this.onclick = null;
}
}

Display data on different browser tabs

The browser has two tabs opened with the different URL.
The data received by one html page from server...
Is it possible to display the same data in another tab which is already opened without reloading...If so how should that has to be done...
Yes, if either:
Your code opened the other tab (via window.open), or
The window has a name (such as one assigned via the target attribute on a link, e.g. target="otherwindow")
Additionally, the window's content must be on the same origin as the document you're interacting with it from, or you'll be blocked by the Same Origin Policy.
1. If you're opening it via window.open
window.open returns a reference to the window object for the window that was opened, which (assuming it's on the same origin) you can do things with. E.g.:
var wnd = window.open("/some/url");
// ...later, when it's loaded...
var div = wnd.document.createElement('div');
div.innerHTML = "content";
wnd.document.appendChild(div);
You can use all of the usual DOM methods. If you load a library in the other window, you can use that as well. (It's important to understand that the two windows have two different global namespaces, they're not shared.)
Here's a full example. I used jQuery in the below just for convenience, but jQuery is not required for this. As I said above, you can use the DOM directly (or another library if you like):
Live Copy | Live Source
HTML:
<button id="btnOpen">Open Window</button>
<button id="btnAdd">Add Content</button>
<button id="btnRemove">Remove Content</button>
JavaScript:
(function($) {
var btnOpen,
btnAdd,
btnRemove,
wnd,
wndTimeout,
wnd$,
newContentId = 0;
btnOpen = $("#btnOpen");
btnAdd = $("#btnAdd");
btnRemove = $("#btnRemove");
updateButtons();
btnOpen.click(openWindow);
btnAdd.click(addContent);
btnRemove.click(removeContent);
function updateButtons() {
btnOpen[0].disabled = !!wnd;
btnAdd[0].disabled = !wnd$;
btnRemove[0].disabled = !wnd$;
}
function openWindow() {
if (!wnd) {
display("Opening window");
wnd$ = undefined;
wndTimeout = new Date().getTime() + 10000;
wnd = window.open("/etogel/1");
updateButtons();
checkReady();
}
}
function windowClosed() {
display("Other window was closed");
wnd = undefined;
wnd$ = undefined;
updateButtons();
}
function checkReady() {
if (wnd && wnd.jQuery) {
wnd$ = wnd.jQuery;
wnd$(wnd).on("unload", windowClosed);
updateButtons();
}
else {
if (new Date().getTime() > wndTimeout) {
display("Timed out waiting for other window to be ready");
wnd = undefined;
}
else {
setTimeout(checkReady, 10);
}
}
}
function addContent() {
var div;
if (wnd$) {
++newContentId;
display("Adding content '" + newContentId + "'");
wnd$("<div>").addClass("ourcontent").html("Added content block #" + newContentId).appendTo(wnd.document.body);
}
}
function removeContent() {
var div;
if (wnd$) {
div = wnd$("div.ourcontent").first();
if (div[0]) {
display("Removing div '" + div.html() + "' from other window");
div.remove();
}
else {
display("None of our content divs found in other window, not removing anything");
}
}
}
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})(jQuery);
2. If you're opening it via a link with target
window.open can find and return a reference to that window:
var wnd = window.open("", "otherwindow");
Note that the URL argument is empty, but we pass it the name from the target attribute. The window must already be open for this to work (otherwise it will open a completely blank window).
Here's the above example, modified to assume you've opened the window via ...:
Live Copy | Live Source
HTML:
Click to open the other window
<br><button id="btnGet">Get Window</button>
<button id="btnAdd">Add Content</button>
<button id="btnRemove">Remove Content</button>
JavaScript:
(function($) {
var btnGet,
btnAdd,
btnRemove,
wnd,
wndTimeout,
wnd$,
newContentId = 0;
btnGet = $("#btnGet");
btnAdd = $("#btnAdd");
btnRemove = $("#btnRemove");
updateButtons();
btnGet.click(getWindow);
btnAdd.click(addContent);
btnRemove.click(removeContent);
function updateButtons() {
btnGet[0].disabled = !!wnd;
btnAdd[0].disabled = !wnd$;
btnRemove[0].disabled = !wnd$;
}
function getWindow() {
if (!wnd) {
display("Getting 'otherwindow' window");
wnd$ = undefined;
wndTimeout = new Date().getTime() + 10000;
wnd = window.open("", "otherwindow");
updateButtons();
checkReady();
}
}
function windowClosed() {
display("Other window was closed");
wnd = undefined;
wnd$ = undefined;
updateButtons();
}
function checkReady() {
if (wnd && wnd.jQuery) {
wnd$ = wnd.jQuery;
wnd$(wnd).on("unload", windowClosed);
updateButtons();
}
else {
if (new Date().getTime() > wndTimeout) {
display("Timed out looking for other window");
wnd = undefined;
updateButtons();
}
else {
setTimeout(checkReady, 10);
}
}
}
function addContent() {
var div;
if (wnd$) {
++newContentId;
display("Adding content '" + newContentId + "'");
wnd$("<div>").addClass("ourcontent").html("Added content block #" + newContentId).appendTo(wnd.document.body);
}
}
function removeContent() {
var div;
if (wnd$) {
div = wnd$("div.ourcontent").first();
if (div[0]) {
display("Removing div '" + div.html() + "' from other window");
div.remove();
}
else {
display("None of our content divs found in other window, not removing anything");
}
}
}
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})(jQuery);

Set title in the window popup

Is it possible to set a title in the window popup?
I have this in javascript:
var popup = window.open('......');
popup.document.title = "my title";
but this does not work..still can't see any title
EDIT: the page popup is displaying is .aspx and it HAS a title tag, but still can't see that on the popup window..
Since popup.onload does not seem to work, here is a workaround: http://jsfiddle.net/WJdbk/.
var win = window.open('', 'foo', ''); // open popup
function check() {
if(win.document) { // if loaded
win.document.title = "test"; // set title
} else { // if not loaded yet
setTimeout(check, 10); // check in another 10ms
}
}
check(); // start checking
I was having problems with the accepted answer until I realized that if you open an existing, slow page that already has a <title> the browser will 1) set your title, then 2) once the document fully loads it will (re)set the popup title with the "normal" value.
So, introducing a reasonable delay (function openPopupWithTitle):
var overridePopupTitle = function(popup, title, delayFinal, delayRepeat) {
// https://stackoverflow.com/a/7501545/1037948
// delay writing the title until after it's fully loaded,
// because the webpage's actual title may take some time to appear
if(popup.document) setTimeout(function() { popup.document.title = title; }, delayFinal || 1000);
else setTimeout(function() { overridePopupTitle(popup, title); }, delayRepeat || 100);
}
var openPopupWithTitle = function(url, title, settings, delay) {
var win = window.open(url, title, settings);
overridePopupTitle(win, title, delay);
return win;
}
None of these answers worked for me. I was trying to open a popup with a PDF inside and kept getting permission denied trying to set the title using the above methods. I finally found another post that pointed me in the correct direction. Below is the code I ended up using.
Source: How to Set the Title in Window Popup When Url Points to a PDF File
var winLookup;
var showToolbar = false;
function openReportWindow(m_title, m_url, m_width, m_height)
{
var strURL;
var intLeft, intTop;
strURL = m_url;
// Check if we've got an open window.
if ((winLookup) && (!winLookup.closed))
winLookup.close();
// Set up the window so that it's centered.
intLeft = (screen.width) ? ((screen.width - m_width) / 2) : 0;
intTop = (screen.height) ? ((screen.height - m_height) / 2) : 0;
// Open the window.
winLookup = window.open('', 'winLookup','scrollbars=no,resizable=yes,toolbar='+(showToolbar?'yes':'no')+',height=' + m_height + ',width=' + m_width + ',top=' + intTop + ',left=' + intLeft);
checkPopup(m_url, m_title);
// Set the window opener.
if ((document.window != null) && (!winLookup.opener))
winLookup.opener = document.window;
// Set the focus.
if (winLookup.focus)
winLookup.focus();
}
function checkPopup(m_url, m_title) {
if(winLookup.document) {
winLookup.document.write('<html><head><title>' + m_title + '</title></head><body height="100%" width="100%"><embed src="' +m_url + '" type="application/pdf" height="100%" width="100%" /></body></html>');
} else {
// if not loaded yet
setTimeout(checkPopup(m_url, m_title), 10); // check in another 10ms
}
}
You can use also
var popup = window.open('......');
popup.onload = function () {
popup.document.title = "my title";
}
Not sure if this will help,
function GetInput() {
var userInput;
var stringOutput;
userInput = prompt('What should the title be?', "");
stringOutput = userInput;
document.title = stringOutput;
}
<button type="button" onclick="GetInput()">Change Title</button>
var win= window.open('......');
win.document.writeln("<title>"+yourtitle+"</title>");
This works for me, tested in chromium browsers.
I ended up creating a setTitle method in my popup window and calling it from my parent page.
//popup page:
function setTitle(t) {
document.title = t;
}
//parent page
popupWindow.setTitle('my title');
Try this, it will work.
var timerObj, newWindow;
function openDetailsPopUpWindow(url) {
newWindow = window.open(url, '', 'height=500,width=700,menubar=no,resizable=yes,scrollbars=yes');
timerObj = window.setInterval("fun_To_ReTitle('~~newTitle~~ ')", 10);
}
function fun_To_ReTitle(newTitle){
if (newWindow.document.readyState == 'complete') {
newWindow.document.title=newTitle;
window.clearInterval(timerObj);
}
}

javascript alert on parent page when child popup closes

I am using javascript window.open method to open lets say http://www.google.com [its always going to be some external url]
I have stored the reference of the window object in a variable, the problem is that variable never gets null on the parent page and I am not able to alert the user that the pop up has been closed.
Here's the code
var winFB;
var winTWt;
var counterFB = 0;
var counterTWT = 0;
var timerFB;
function openFB() {
if (counterFB == 0) {
winFB = window.open("http://www.google.com");
counterFB = 1;
}
if (counterFB > 0) {
alert(winFB);
if (winFB == null) {
counterFB = 0;
clearTimeout(timerFB);
alert("Window Closed");
}
}
timerFB= setTimeout("openFB()", 1000);
}
I can not put any javascript code on the pop up/child window.
Hope someone can help me on this
The window variable doesn't get nulled out when it's closed, however its .closed property is true, so just change your check to be for that property, like this:
var winFB;
var winTWt;
var counterFB = 0;
var counterTWT = 0;
var timerFB;
function openFB() {
if (counterFB == 0) {
winFB = window.open("http://www.google.com");
counterFB = 1;
}
if (counterFB > 0) {
if (winFB.closed) {
counterFB = 0;
clearTimeout(timerFB);
alert("Window Closed");
}
}
timerFB = setTimeout(openFB, 1000);
}
Also note the setTimeout() change, pass a function in whenever possible (almost always) rather than a string, you'll have a lot less problems with scoping.
//in the parent
winFB = window.open("http://www.google.com");
//in the child window you can access
var _parent = window.opener.document;
//also use the onunload event in the child window
onunload="doSomething()"
hope this gives you some direction..

Check if popup window is already open

How can I modify this so it checks and if a popup window is already open?
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=100');");
}
/////////////Edit No2
var options = "toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=100";
var popup = window.open(URL, "popup", options);
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=100');");
}
My js call
<a id="floating_link" href="javascript:popUp('MyPage.html')">Player</a>
Use the same id for the window, which is the name of the window, to reuse it if it exists.
http://www.w3schools.com/jsref/met_win_open.asp
var options = "toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=100";
var popup = window.open(URL, "popup", options);
To do this with an anchor tag you just set the target
If you set an anchor tag's target target="myopup" it will use that same window if it exists
My answer is to this question linked to here.
Check the following code.
You can use onbeforeunload to get a callback before the window unloads.
To check if this is due to window.close do this
setTimeout(function(){
if(anc.closed) console.log('closed');
else console.log('refreshed');
},1000); // to check after the window closed
FULL CODE
var anc = window.open('https://stackoverflow.com');
var anc.onbeforeunload = function() { // called before closing the window.
setTimeout(function() {
if (anc.closed) console.log('closed');
else console.log('refreshed');
}, 1000); // to check after the window closed
}

Categories

Resources