I am new to javascript.
This is a download confirm page. I have a download button on the page.
I want to capture the close window event to delete the temp pdfs which is handled in AjaxHandler.ashx
.
With the code below, I find the deletePDF
will be executed when the window init, when the download bottun click but will not be executed when close window.
I know the beforeunload
will be activate in several cases, but why when I close window it doesn't effect? (has solved, update below the codes)
if (window.attachEvent) {
window.attachEvent("beforeunload", deletePDF());
}
else if (window.addEventListener) {
window.addEventListener("beforeunload", deletePDF(), false);
}
function deletePDF(event) {
var link = "Handler/AjaxHandler.ashx?filestring=" + getQueryStringByName("filestring");
$.ajax({
type: "get",
cache: false,
url: link,
beforeSend: function (XMLHttpRequest) {
},
success: function (data, textStatus) {
},
complete: function (XMLHttpRequest, textStatus) {
},
error: function () {
}
});
}
Update
I correct the deletePDF()
to deletePDF
in addEventListener
by Alon Eitan comment point.
Now the code will jump into deletePDF
when I click download button and click 'X' close window.
I try the clientY
to restrict the event. But it can't react to the close window action. (I know I miss the cases close window by keyboard, hope someone have better solutions)
if (window.event.clientY < 0 )
...
The button like :
<asp:Button ID="btnDownload" runat="server" CssClass="Button" Text="Download" Width="100px" CommandName="download" />
Update
By Alon Eitan's last advise, I try to use the code below to exclude the asp button.
Both .on().off()
and .bind().unbind()
can't trigger when window close in Edge, Chrome, FF. I also try add async:false
to ajax.
But in IE11, .bind().unbind()
trigger when window close and button click, .on()
get errors
Object doesn't support property or method 'on'
$("[id$='_btnDownload']").click(function () {
$(window).off("beforeunload");
// $(window).unbind("beforeunload");
})
$(window).on('beforeunload', function() {
//$(window).bind('beforeunload', function() {
...
})
Update
According to the anwser javascript - Disable AddEventListener on Submit - Stack Overflow,
I try to set a flag like the the submitting
, but I find that if I use a flag by checking click
button, when I close window after the button, the handler will not be execute because the button
flag has been set true
. But I want to check if the button click when everytime the addEvenListener be triggered.
Sorry for my poor English, wish I can be understood.
Thanks.