'i want call a function when click close browser ... element of button close browser?
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>
Solution 1:[1]
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 aelements 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});
});
Solution 2:[2]
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%20tab%20or%20window%20closing,the%20tab%20or%20the%20browser.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Louys Patrice Bessette |
| Solution 2 |
