This is my javascript code ...i want call a function when click close browser at window.close().But not working..You can help me.Thank so much.<3
<script>
$(document).ready(function () {
var typeChange = false;
$(document).on("keyup", 'form input', function (e) {
typeChange = true;
});
$(document).on("change", 'form select', function (e) {
typeChange = true;
});
function changeURL() {
window.addEventListener("beforeunload", function (e) {
if (typeChange) {
e.preventDefault();
e.returnValue = "";
}
}, {once : true});
}
$(document).on('click', '.sidebar-menu a', function() {
changeURL();
});
// window.addEventListener("close", function () {
// changeURL();
// });
// window.close() = function() {
// changeURL();
// };
});
</script>
CodePudding user response:
You were quite close... But there are two things:
- You have to register the event listener for beforeunload when the page loads... Not when it is about to unload ;)
- It won't be necessary to use an event handler on the
.sidebar-menu a
elements if those links are making the browser to navigate.
So here is the code that should work for you:
$(document).ready(function () {
var typeChange = false;
$(document).on("keyup", 'form input', function (e) {
typeChange = true;
});
$(document).on("change", 'form select', function (e) {
typeChange = true;
});
window.addEventListener("beforeunload", function (e) {
if (typeChange) {
e.preventDefault();
e.returnValue = "";
}
}, {once : true});
});
CodePudding user response:
I'm afraid 'window' object doesn't have event 'close', howerver it has event 'beforeunload'. check belows codes copied from the below link.
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
});
Below artilce explains it in much more details
https://www.geeksforgeeks.org/how-to-detect-browser-or-tab-closing-in-javascript/#:~:text=A tab or window closing,the tab or the browser.