close window exxternal javascript code example
Example 1: javascript close window
<!DOCTYPE html>
<html>
<body>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
var myWindow;
function openWin() {
myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}
function closeWin() {
myWindow.close();
}
</script>
</body>
</html>
Example 2: on window close give alert javascript
let disableConfirmation = false;
window.addEventListener('beforeunload', event => {
const confirmationText = 'Are you sure?';
if (!disableConfirmation) {
event.returnValue = confirmationText;
return confirmationText;
} else {
disableConfirmation = false;
}
});
After Confimation if you want to send any ajax request and you have used jquery
$(window).on('unload', function() {
axios
.get('ajax_url')
.then(response => {});
});
And if no jquery is used you can use navigator, it require navigator library
navigator.sendBeacon(url, data);