Reputation: 290
I write code to open a popup in new window. I open this window for few seconds after that it will close automatically.What I want is if somebody close it before that limit of time. I will detect it and show him message. Here is code I am using
$(document).ready(function() {
var myWindow;
$("#idview").click(function() {
var vidurl = $('#vurl').val();
counter();
myWindow = window.open(vidurl, "popupWindow", "width=600, height=400, scrollbars=yes");
});
function counter() {
var n = $('.c').attr('id');
var c = n;
$('.c').text(c);
setInterval(function() {
c++;
if (c <= 41) {
$('.c').text(c);
}
if (c == 41) {
$('.c').text(n);
}
}, 1000);
}
setInterval(function() {
myWindow.close();
}, 45000);
window.onbeforeunload = closingCode;
function closingCode(){
alert('hitme');
return null;
}
});
I try to use window.ununload
but it is not working. can anybody please tell me how to get if somebody is going to close the browser popup?
Thanks
Upvotes: 1
Views: 1206
Reputation: 12085
1st : You need to bind the onbeforeunload
event to the window AFTER
it is opened
.
2nd : so move the onbeforeunload
event code to inside the click event
function
3rd : Window.onbeforeunload
change to myWindow.onbeforeunload
var myWindow;
$("#idview").click(function() {
//var vidurl = $('#vurl').val();
var vidurl = "google.com";
counter();
myWindow = window.open(vidurl, "popupWindow", "width=600, height=400, scrollbars=yes");
myWindow.onbeforeunload = function closingCode(){
alert('hitme');
return null;
}
});
Upvotes: 1
Reputation: 12181
Here you go with a solution https://jsfiddle.net/rs01x0oy/
var myWindow;
$("#idview").click(function() {
var vidurl = $('#vurl').val();
counter();
myWindow = window.open(vidurl, "popupWindow", "width=600, height=400, scrollbars=yes");
myWindow.onbeforeunload = function(){
console.log("Closed");
};
});
function counter() {
var n = $('.c').attr('id');
var c = n;
$('.c').text(c);
setInterval(function() {
c++;
if (c <= 41) {
$('.c').text(c);
}
if (c == 41) {
$('.c').text(n);
}
}, 1000);
}
setInterval(function() {
myWindow.close();
}, 45000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="idview" type="submit">
Submit
</button>
Upvotes: 0
Reputation: 511
You can use onbeforeunload like this :
window.onbeforeunload = function (e) {
var e = e || window.event;
};
More reference : https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
Even possible duplicate of : javascript detect browser close tab/close browser
Upvotes: 2