javascript - 从 window.onbeforeunload() 上传文件

标签 javascript jquery session

在我的应用程序中,我需要确保如果用户离开应用程序(通过关闭选项卡、关闭浏览器或导航到另一个页面),他们是否尝试返回应用程序(使用后退按钮、历史记录或键入链接)他们将被引导到一个屏幕,使他们重新登录。

我想我已经解决了这一切:

  1. 在每个页面上检查我的 session 是否可用。
  2. 如果是,请继续。如果没有,请重定向到“您必须重新登录”。页。
  3. 在 window.onbeforeunload() 事件上,运行 destroy.php 脚本。
  4. 销毁脚本会终止 session 。

但是我无法从 onbeforeunload() 事件加载我的销毁脚本。

这是索引文件,开始工作:

<?php

/***********************
INDEX for CloseTab test
************************/

// Start the session
echo "<pre>";
echo "Starting session now...";
session_start();

// Put something in the variable that we can get on another page
$_SESSION["name"] = "Joe";
echo "\nJust set session var 'name' to 'Joe'.";

?>

<!-- Open that other page -->
<a href= <?php echo "home.php"; ?> > Click here to open Home page</a>

这是主页,只是为了有地方可以去测试 session :

    <head>

        <!-- ***********************
        HOME for CloseTab test
        ************************** -->

        <!-- Link to jQuery file  -->
        <script   src="https://code.jquery.com/jquery-3.1.1.min.js"   
              integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   
              crossorigin="anonymous"></script>

        <!-- Link to our custom js code.. -->
        <script type="text/javascript" src=<?php echo "my_scripts.js></script> 

    </head>

    <?php

    // Start the session
    session_start();

    // See if there is any indication that a session is not available.
    // Test with closing tab, closing browser, navigating away from page.
    // We want to see this message if the user is coming here from anywhere except the index page.
    // Test back button, typing the URL, browser history.
    if ( (!isset($_SESSION)) || (session_status() == PHP_SESSION_NONE) || (count($_SESSION) < 1) ) {
        echo "<pre>";
        echo "Your session is not longer active.  Log in again.";
        echo "\n\nPretending to go to a login page...";
        exit;
    }

    ?>

    <!-- If the session is good, we MUST have come from index page, and can access the session var. -->
    <div class="container">
        <h1>Home Page</h1>
        <h2>Here is the name from the session var: <?php echo $_SESSION["name"]; ?> </h2>
    </div>

<div>
    <h3><a href= <?php echo "destroy.php"; ?> > Click here to log out</a></h3>
</div>

</html> 

这是我的 JavaScript 代码:

/***********************
my_scripts.js
************************/

console.log("in js file");

// Before a page unloads, run the destroy code
window.onbeforeunload = function() {
    console.log("inside onbeforeunload");             // I get this to print

    // Try to execute with AJAX call                  // Nothing in the middle seems to be running
    $.ajax({
        type: "GET",
        url: "destroy.php",
        async: false                     
     });

    // Try with jQuery syntax
    $("container").load("destroy.php");

   console.log("Got this far");                       // I get this to print
}

这是我尝试加载的销毁代码:

<?php

/******************************************************************
Destroy
- Clears the session var and destroys the session if user leaves app.
******************************************************************/

// Unset all of the session variables and destroy the session.
session_start();
$_SESSION = array();
session_destroy();

?>

<script type="text/javascript">
    // Place message in the console that we can see even if the window closes.
    console.log("DONE!  Session destroyed.")
</script>

最佳答案

您需要小心使用onbeforeunload。浏览器不允许您在此事件中执行过多操作。

如果要进行AJAX调用,则需要添加async: false。这通常是不鼓励的,但在这里,如果调用是异步的,那么浏览器可能会在调用完成之前完成事件并关闭页面。

$.ajax({
    type: "GET",
    url: "destroy.php",
    async: false
 });

关于javascript - 从 window.onbeforeunload() 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43121411/

相关文章:

javascript - 完整日历未在 Bootstrap 选项卡中自动加载?

Jquery 在页面加载/调整大小时调整 div 的大小

http - 每个 IP 地址或每个浏览器的 JSP session

asp.net - ASP.net 4.0 session ID 的最大长度是多少 - 存储为 varchar、char 或 nvarchar?

javascript - Angular 2 + 如何使用相同的选择器选择和循环多个元素(elementRef.nativeElement)

javascript - 使用 AJAX 将数组发布到 MVC C#

javascript - 模态中的TinyMCE,模态在将数据传递给div后不会重新打开

javascript - 检查字符串是否遵循 JavaScript 中给定的模式

javascript - 在 jspdf 中没有获得所需的输出

php - 在我的实时应用程序上获取看起来很像 session 冲突的行为。不知道为什么