Tom
Tom

Reputation: 2044

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?

Upvotes: 2

Views: 12083

Answers (2)

Tom
Tom

Reputation: 2044

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>

Upvotes: 1

allicarn
allicarn

Reputation: 2919

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.

Upvotes: 1

Related Questions