用户尝试重新加载页面或单击“返回”按钮时自动提交表单

时间:2018-09-17 05:51:30

标签: javascript php

当用户尝试重新加载页面或返回页面时,我在提供我想要的考试时,我正在使用在线考试门户网站,请自动提交带有警告消息的表格。

<script type="text/javascript">

  window.onload = function() {
    $('#form_id').submit();
   return true;

     // if I use alert here alert work but form not submitting

  };

  </script>

2 个答案:

答案 0 :(得分:1)

您可以使用onbeforeunloadevent.currentTarget.performance.navigation.type

<body onbeforeunload ='checkRequest(e)'>
   //rest of code
</body>

function checkRequest(event){
   let __type= event.currentTarget.performance.navigation.type;
    if(__type === 1){
      // alert("Browser refresh button is clicked...");
   }
else if(__type ==2){
    //Browser back button is clicked
   }
}

您也可以访问此link

答案 1 :(得分:0)

从@brk的答案中获取帮助。
参考链接:https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

与停止页面重新加载有关的词: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Syntax

<?php
    echo '<br>GET PARAMETERS=<pre>'. print_r($_GET, true) .'</pre><br>';
?>
<html>
    <head>
        <title>Untitled Document</title>
    </head>
    <body onbeforeunload ='checkRequest(event)'>
        ABC
        <form name="frm1" id="frm1" action="">
            <input type="text" name="text1" id="text1" value="<?php echo ( isset($_GET['text1']) ? $_GET['text1'] : '' ) ?>">
        </form>
        <script type="text/javascript">
            function checkRequest(event){
                event.preventDefault();
                event.returnValue = '';
                var __type= event.currentTarget.performance.navigation.type;
                if(__type === 1 || __type === 0){
                    // alert("Browser refresh button is clicked...");
                    document.getElementById('frm1').submit();
                }
                else if(__type ==2){
                    alert("Browser back button is clicked...");
                }
            }
        </script>
    </body>
</html>