React | How to Detect Page Refresh (F5)

React | How to detect Page Refresh (F5)

Place this in the constructor:

if (window.performance) {
if (performance.navigation.type == 1) {
alert( "This page is reloaded" );
} else {
alert( "This page is not reloaded");
}
}

It will work, please see this example on stackblitz.

React app detect if user refresh window or navigated away

The best way to detect a page reload is to use window.performance.navigation which returns an object for the page containing two key-value pairs { redirectCount: 0 , type: 0 } shown below:

console.log(window.performance.navigation)

How can i handle page refresh event in React.js

Try this code it's work for me

 window.onbeforeunload = function () {
if ("Some condition") {
return '';
}
}.bind(this);

detect browser refresh/F5/right click reload in angular 5

You cannot prevent the user from not running or editing client-side JavaScript code. Since this is a security requirement against the interest of that particular user, the solution must be server-side:

On the server, after getting the wrong answer, mark the user's profile as such. You may need an additional table in your database joining users and questions for that.

Whenever the user loads the question or submits it, first check the user's flag. If it's set, error out immediately.

Note that this behavior is quite hostile to the user. For instance, the user may accidentally touch Enter too soon, and will be shut out by your system.

Detecting a refresh event in react

If you want to detect a refresh event, It has nothing to do with React, instead use plain Javascript event handler called window.onbeforeunload

window.onbeforeunload = (e) => {
// I'm about to refresh! do something...
};

However I don't think it's the proper approach to store Redux store, instead you can do something like:

// load state from localStorage
const loadState = () => {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined; // reducer will return Redux state, as localstorage is null.
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
};

const saveToLocalStorage = (state) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (err) {
// ignore error
}
};

store.subscribe(() => {
saveToLocalStorage(store.getState()); // save current state to localstorage.
});


Related Topics



Leave a reply



Submit