Javascript 防止在提交时意外关闭浏览器窗口

Javascript 防止在提交时意外关闭浏览器窗口,javascript,php,forms,browser,Javascript,Php,Forms,Browser,我有一个页面,用户可以在上面提交包含视频的表单。我在上传视频时放了一条“请稍候,现在上传”的消息,但显然,这还不够 因此:我想确保用户不会意外地离开页面,因此我使用了以下代码: window.onbeforeunload = function() { return "Please make sure, the video has finished uploading before closing this window"; }; 只是有一个问题:系统包含两个单独的.php文件;一张表

我有一个页面,用户可以在上面提交包含视频的表单。我在上传视频时放了一条“请稍候,现在上传”的消息,但显然,这还不够

因此:我想确保用户不会意外地离开页面,因此我使用了以下代码:

window.onbeforeunload = function() {
    return "Please make sure, the video has finished uploading before closing this window";
 };
只是有一个问题:系统包含两个单独的.php文件;一张表格和一个上传/感谢页面。这意味着,如果我将代码放在表单上,它会过早地执行代码(当按下submit按钮时),如果我将代码放在send.php-file中,它会执行得太晚,因为必须在运行head标记之前上载视频

有什么好主意吗


另外,一种可能的解决方案是将代码放在表单页面上,并使用AJAX和文件处理能力解决方案调用页面,但我感觉这种解决方案可能会导致视频丢失-因此我很安全。

当用户提交表单时,您能添加JS代码吗

<form action="upload.php">
  <input type="file" name="myfile" />
  <input type="submit" />
</form>

upload.php

<?php
  // Validate the data, copy the file, etc.

  echo '<script>window.onbeforeunload = function(e) { return "Please make sure, the video has finished uploading before closing this window"; }</script>';
?>

这应该行得通。但是,我认为你应该选择离开:

<?php
  echo '<script>window.onbeforeunload = function(e) { return confirm("Do you want to leave?"); }</script>';
?>

情况已解决

我删除了按钮的提交功能,并将其替换为:

<input type="button" name="button" id="button" value="Send video" onclick="sendInformation();" />
它还有一个不希望出现的效果,即onbeforeunload代码在upload.php页面完全加载的那一刻失效,因此在关闭成功的上载时,用户不会被询问两次


它工作得完美无缺。

唉,它没有工作。在成功上载之前,不会执行代码。然而,我5分钟前才让它工作;请看上面的答案。。。
document.getElementById("pleasewait").style.visibility = 'visible';
document.getElementById("myForm").submit();
window.onbeforeunload = function(e) {
   return "Please make sure, the video has finished uploading before closing this window."; 
};