Does someone know the best solution to make the code below work ('crosswindow') to track multiple windows opened by the function openNew() ?
It is currently only capable of tracking one window only. I tried some stuff with objects but Im not an expert. All suggestions are welcome.
Javascript:
function openNew(href){
timer = setInterval('polling()',500);
win = window.open(href, '_blank');
url=href;
openTime=0;
clickTime= (new Date()).getTime();
}
function polling(){
if (win && win.closed) {
var closingTime = (new Date()).getTime();
var diff = ((closingTime-clickTime)/1000);
clearInterval(timer);
console.log(url+" closed after " + diff + " secs");
}
}
HTML
<a href="http://google.com" onClick="openNew('http://google.com'); return false;" target="_blank">google</a>
<a href="https://facebook.com" onClick="openNew('https://facebook.com'); return false;" target="_blank">facebook</a>
The goal in the end is to be able to open multiple new windows from the parent page and when a child window gets closed, its logged in the parent window.
I have made a pen with a simulation of the console (to avoid infinity loop alerts ) http://codepen.io/anon/pen/EjGyQz?editors=101
So, you just need to wrap your call to polling in a closure, and pass in all of the variables to it, so it isn't overwriting the old ones:
http://codepen.io/anon/pen/GJPqwm?editors=101
function openNew(href){
var current = window.open(href, '_blank');
var clickTime= (new Date()).getTime();
(function(win, url, clickTime) {
var timer = setInterval(function() { polling(win, timer, url, clickTime) },500);
})(current, href, clickTime);
}
function polling(win, timer, url, clickTime){
if (win && win.closed) {
var closingTime = (new Date()).getTime();
var diff = ((closingTime-clickTime)/1000);
clearInterval(timer);
//replace console with div log
document.getElementById('log').innerHTML += url+" closed after " + diff + " secs<br>";
}
}