Prevent Chrome from automatically restoring the previous browsing session

Is there a way to prevent Chrome from restoring the session when reopening a closed page? Possibly using a special header?

My company app relies heavily on user state, and I need to log employees out and delete all relevant data if they are inactive for 60 minutes. The issue is that Chrome automatically reopens the page exactly where it was left off, making it difficult for my website to detect the inactivity. The setTimeout function won't trigger until another 50 minutes pass.

I've considered some unconventional solutions but would prefer a method to instruct Chrome not to restore old sessions and instead treat each opening as a fresh start. Perhaps disabling caching through JavaScript could work?

Edit: I am serving the Angular 9 static HTML and JavaScript using IIS.

Answer №1

It seems like you are utilizing a static website with no backend functionality. While the specifics were not mentioned, it is assumed that either sessionStorage or localStorage is being used for authentication purposes. To manage idle time, a timer can be implemented upon user login and a localStorage can track the duration of inactivity.

let current_date = new Date();
let milliseconds = current_date.getTime(); // Retrieves milliseconds since 1970/01/01
localStorage.setItem("idle_time", milliseconds);

To constantly monitor if the session has expired, periodically run this function using something akin to setInterval() at intervals such as every 10, 20, 30, or 60 seconds based on your preference.

function check_if_session_expired() {
  let max_idle_minutes = 60;
  let current_milliseconds = current_date.getTime();
  let stored_idle_time = localStorage.getItem("idle_time");
  let minutes_to_milliseconds = 1000 * 60;
  if ((Math.round(current_milliseconds / minutes_to_milliseconds) - Math.round(stored_idle_time / minutes_to_milliseconds)) >= max_idle_minutes) {

    console.log("expired");
    // Perform logout actions and clear sessionStorage/localStorage if desired.
  } else {
    localStorage.setItem("idle_time", current_milliseconds);
  }
}

Cookies can serve the same purpose effectively.

Answer №2

If you're looking to remove the session from the server side, take a look at this PHP code snippet below. Feel free to customize it according to your needs and requirements.

<?php

session_start();

//Expire the session if user is inactive for 60 minutes or more.
$expireAfter = 60;

//Set the current timestamp as the user's latest activity
$_SESSION['last_action'] = time();

//Check if the "last action" session variable has been set
if(isset($_SESSION['last_action'])){

    //Calculate the seconds since the user was last active
    $secondsInactive = time() - $_SESSION['last_action'];

    //Convert minutes to seconds
    $expireAfterSeconds = $expireAfter * 60;

    //Check if the user has been inactive for too long
    if($secondsInactive >= $expireAfterSeconds){
        //Destroy the user's session if inactive
        session_destroy();
        unset($_SESSION);
        header("Location: http://".$_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT']."/example/login.php");
        exit;
    }

}

This is just a basic implementation that can be customized further to suit your specific requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

Using Ajax to send data to a PHP script

I am interested in implementing an AJAX call to a PHP script each time a specific button is clicked. The buttons correspond to different directions - right, left, top, and bottom, represented by divs named r, l, t, and b. I have attempted the code below ...

Error with infiniteCarousel in Internet Explorer versions 7 and 8 when using jQuery

Hello everyone! I've run into a little issue with some jQuery code I'm using. It was working fine before, but after making several changes and improvements, I can't seem to figure out what the problem is. I keep getting JS errors in both IE7 ...

Tips for fixing Unexpected Token Error in a nextJS project

I recently started working on a brand new "next.js" project and was eager to dive into coding. However, I found myself stuck for hours trying to resolve the following error message. To kick things off, I decided to use a reference code snippet which looke ...

The connection between two arrays remains intact even after using the .push() method in JavaScript or Vue.js

I need help setting up two arrays containing dates. The first array should have the dates in string format, while the second array should contain the same dates but as date objects. methods: { test() { let employments = [ { begin: ...

What is the best way to store and present data dynamically in D3.js?

Currently, I'm engaged in a project involving my Raspberry Pi that focuses on a sensor collecting data continuously. My objective is to save this data in a specific format such as SQL, CSV, JSON, or any other suitable option, and then present it visua ...

Utilizing AJAX in Wordpress to Dynamically Update HREF Links

My website now has AJAX functionality, and you can see a live example at www.mathewhood.com. I am interested in changing the URL format when clicked from To something like , without the /sitefiles/ for security reasons. Below is my code. If anyone is ex ...

What is the best approach to building this using Angular?

Greetings, this marks the beginning of my inquiry and I must admit that articulating it correctly might be a challenge. Nevertheless, here's my attempt: Within the following code snippet, there lies an element that effectively fills up my designated ...

Is it possible to remove a particular div after clicking the delete button, especially if multiple divs are displayed upon clicking the add

var count = 2; var countMax = 5; function adddt() { if (count > countMax) return; document.getElementById('dt-' + count + '').style.display = 'block'; count++; } <link href="https://maxcdn.bootstrapcdn.com/bo ...

Searching the JSON file by its value using Waterline

I am struggling with locating model instances based on the nested address attribute in one of my models. attributes: { address: { type: 'json' } } I have attempted various queries to find model instances located in the same city: Model ...

Is there a method to retrieve the bounds (northeast and southwest) of the map display when there is a change in the bounds, center, or view area?

In my NextJs project, I am utilizing the TomTom Map SDK to implement a feature where, upon loading the map based on its bounds, I query for nearby restaurants in that specific area. Additionally, when there are zoom or drag events on the map, I want to mak ...

Enhancing the efficiency of a TypeScript-written file content parsing class

Seeking advice on optimizing a typescript module used by a VSCode extension. This module accepts a directory and parses the content within the files, which can be time-consuming for directories with a large number of files. To avoid copying the entire cla ...

Learn the process of extracting a particular value from JSON data and displaying it in HTML by utilizing AngularJS's ng-repeat directive

As a newcomer to angularjs, I am encountering difficulties retrieving and displaying a specific value from a json file in order to showcase it on my view page using angularjs ng-repeat for image source. My goal is to repeat the json file based on a particu ...

Orchard's TinyMce now supports a drop event with jQuery integration

Currently in the process of constructing a website using Orchrad. I have implemented the tinymce4 html editor for building landing pages without any issues thus far. However, my current challenge involves capturing the jQuery drop event within the TinyMce ...

Drupal - How can I update a view after users rate with the Fivestar module?

I'm working on a website where users can vote on the front page and I need to update a specific view on the same page after each vote. Currently, I have the following code in my page.tpl.php file: <script type="text/javascript> function update ...

My backend axios post request is not returning any data to my external API. What could be the issue?

I've encountered an issue where I'm attempting to transmit data from my client-side using an ajax call to my backend axios post request, which is responsible for posting data to an external API URL. Despite receiving a 200 status code, none of th ...

No data returned from Ajax GET request

Utilizing Ajax with JavaScript, I am processing data on a PHP page using the GET method. Is it possible to send data from the PHP page when the GET query is empty? My goal is to have a live search feature that filters results based on user input. When a us ...

Incorporating React into a non-React website

I am currently working on a project where the server renders all views using the Twig template engine. Therefore, I tend to write all my scripts within the .twig templates. Take, for instance, the aside-buttons.twig template: <div class="aside-butto ...

Generate various 2-dimensional arrays of objects in JavaScript, with each object sharing identical properties

Is there a way to efficiently create two 2-D arrays, where each element of the array is an object with unique properties? These arrays are of different sizes and each cell has different properties. var gridcell = []; var regionalcell = []; I have managed ...

Tips for adjusting the search bar's position on a mobile device when it is activated by the user

I need help with an open source project where I am developing a search engine using Angular. When using smaller screen sizes, the search bar is positioned in the middle but gets hidden behind the keyboard terminal when clicked on. Can anyone advise on ho ...