简体   繁体   中英

sessionStorage.clear() not working

I'm using sessionStorage successfully in a project, with one caveat: I can't eliminate the storage with the clear() operator, as documented.

I'm doing this when logging out of the administrative mode of my site, which involves clicking on a Log Out item in a list, like this:

<li><a href="admin_logout.php">Log Out</a></li>

The admin_logout.php file then destroys session variables, etc., and then redirects to the home page of the site. Its previous form, which works, is:

<?php
session_start();
session_destroy();
@header('Location:./');
exit;
?>

That all works fine. What I can't seem to integrate into the routine is clearing the sessionStorage. For the text of my admin_logout.php file, I've tried:

<?php
session_start();
?>

<script>
sessionStorage.clear();
</script>

<?php
session_destroy();
@header('Location:./');
exit;
?>

...as well as:

<?php
session_start();

echo '<script>';
echo 'sessionStorage.clear();';
echo '</script>';

session_destroy();
@header('Location:./');
exit;
?>

Perhaps pointing to the root cause is that when I've placed:

?>
<script>
alert("HELLO");
</script>
<?php

...within this script, the alert is never executed, yet everything else is. How can I invoke the <script> based sessionStorage.clear() operation to clear my session storage items within the routine listed above?

I think it's because you're redirecting on the server-side and the sessionStorage.clear() is happening on the client side. I believe you're redirecting before that gets a chance to run.

Allicam was correct; I needed to encapsulate the storage clearing code in a callback function:

<?php
session_start();
session_destroy();
<script type="text/javascript">

function firstFunction(_callback){
    sessionStorage.clear();
    _callback();
}

function secondFunction(){
    firstFunction(function() {
        window.location = './';
    });    
}
secondFunction();
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM