如果上传正在进行中,如何触发window.onbeforeunload警告

时间:2014-09-29 16:27:42

标签: javascript onbeforeunload

使用以下JavaScript函数上传文件:

function uploadFile(formdata) {
    var xhr = new XMLHttpRequest();

    xhr.upload.addEventListener("progress", progressHandler, false);
    xhr.addEventListener("load", completeHandler, false);
    xhr.addEventListener("error", errorHandler, false);
    xhr.addEventListener("abort", abortHandler, false);
    xhr.open("POST", "upload.php");
    xhr.send(formdata);
}

如果用户在上传仍在进行时尝试重新加载或关闭浏览器窗口,我很难弄清楚如何实施window.onbeforeunload警告消息。

1 个答案:

答案 0 :(得分:1)

设置一个标记 - 我将使用window,但您应该使用您的应用范围。

window.uploading = false;

window.onbeforeunload = function () {
    if (window.uploading) {
        return 'You are uploading! CHILL OUT!';
    }
};

function uploadFile(formdata) {
    var xhr = new XMLHttpRequest();

    window.uploading = true;
    xhr.upload.addEventListener("progress", progressHandler, false);
    xhr.addEventListener("load", completeHandler, false); // complete handler sets uploading to false
    xhr.addEventListener("error", errorHandler, false);
    xhr.addEventListener("abort", abortHandler, false);
    xhr.open("POST", "upload.php");
    xhr.send(formdata);
}