0

I am trying to show the text "Hello" only on first load. If user close window and opens again then it should show again. But while in the window and navigating to page should not show the "Hello".

Scenario:

  • Enter url: /hello
  • Show "Hello"
  • Enter url: /bye
  • Enter url: /hello
  • Don't show "Hello"
  • Close window
  • Open window
  • Enter url: /hello
  • Show "Hello"

What I am trying it withe unload event:

const firsttime = localStorage.getItem('firsttime')
useEffect(() => {
  window.addEventListener('unload', () => {
    localStorage.removeItem('firsttime')
  })
  const t = setTimeout(() => {
    localStorage.setItem('firsttime','1')
  },2000)
  return () => {
    clearTimeout(t)
    window.removeEventListener('unload', null)
  }
},[firsttime])
return !firsttime && "Hello" || null

This is working fine when I navigate to the pages, the "Hello" is shown for the first time and after that it is not being shown. But when I directly enter the url (it gets refreshed), the "Hello" is shown. I don't want to show the "Hello" on any refresh. I only want to show it if the window is closed and opened again. So, how can I detect the window is opened for the first time and also after closing it.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
gacat
  • 116
  • 1
  • 13
  • I don't get the use of using local storage why don't you just create a function that returns hello then call it onload? – seriously Jun 09 '21 at 20:08
  • I tried just with onload, but could not get what I expected so tried using localStorage but still no help. – gacat Jun 09 '21 at 20:10
  • I thought unload will do on window close, how to do it? – gacat Jun 09 '21 at 20:11
  • Give the user a localstorage cookie on first load and check for that cookie on next load; as long as the user doesn't clear their cache they won't see Hello again. – Nathaniel Flick Jun 09 '21 at 20:12
  • It is actually when current window unloads. Reloading page unloads current window. Closing a tab will first unload the current window – charlietfl Jun 09 '21 at 20:13
  • @NathanielFlick I need to show hello again after window is closed and re-opened. – gacat Jun 09 '21 at 20:13
  • As soon as you navigate to a different URL the page "unload" is triggered. It does not only change when you close the tab (see [definition and usage](https://www.w3schools.com/jsref/event_onunload.asp)). Try using React Router and storing the `firstTime` value in the state of a higher level component. – Luka Kralj Jun 09 '21 at 20:13
  • @LukaKralj I'm using react-router that's why on navigation it works as I mentioned in my question. But the problem occurs when refresh. – gacat Jun 09 '21 at 20:14

3 Answers3

0

I think you're on the right track with localStorage, you might just need to figure out when it's actually executing your code.

Your event listener for the onload event should be outside of your react component, and I believe it should be initialized with the main application.

Then I would recommend setting your visit flag the moment you show your first message.

Edit 1 After a little more research, it seems like the problem might be your unload event. It seems like both refreshing and closing the page will trigger this event. So the issue seems to be the removal of the flag, which at this point it will be happening all the time. I wonder if you can place a timer instead, like storing the time it was visited and compare it every time you load the page, and only show the Hello after 5 mins or so...

Edit 2 I was looking at another answer: Check if page gets reloaded or refreshed in JavaScript and I modified the code, I think this should work:

window.addEventListener('unload', () => {
  localStorage.removeItem('pageVisited');
});

var MyHelloOnFirstLoad = React.createClass({

  getWellcomeMessage(){
    let pageHasBeenVisited = localStorage.getItem('pageVisited') == 1;

    if(pageHasBeenVisited || performance.navigation.type == performance.navigation.TYPE_RELOAD)
{
     return null;
}
      localStorage.setItem('pageVisited', '1');
      return <h1>Hello</h1>;

  },
  
  render(){
    return(
      <div>
        {this.getWellcomeMessage()}
      </div>      
    );
  }

});
LeoSanchez
  • 144
  • 1
  • 6
  • What you say about this comment from charlietfl? `It is actually when current window unloads. Reloading page unloads current window. Closing a tab will first unload the current window` – gacat Jun 09 '21 at 20:51
  • 1
    He is totally correct and this answer is incorrect XD – LeoSanchez Jun 09 '21 at 20:54
  • I just added an extra check to see if the page was reloaded, I learned something XD. This assumes that if you're reloading the page, you already visited it. I guess you could just add that extra line of code to your original piece of code. – LeoSanchez Jun 09 '21 at 20:59
  • I had no luck even with that. Anyways, I will re-try it tomorrow and let you know. Going to take a sleep for now. – gacat Jun 09 '21 at 20:59
-1

The easy solution is to first check if you have visited the page then if not alert hello then set visited to true.Then on window close, you set visited to false. The next time it opens it alerts hello. This includes jquery

$(document).ready(function() {
if(!localStorage.visited) {
    alert('hello')
    localStorage.visited = true;
}
});

window.onbeforeunload = function(){
   localStorage.visited = false;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
Nimantha
  • 6,405
  • 6
  • 28
  • 69
seriously
  • 1,202
  • 5
  • 23
-1

Consider using sessionStorage instead of localStorage.

See documentation

Luka Kralj
  • 446
  • 3
  • 12