0

I want to add a message for example: If the user leaves the browser tab, the message "Looks like you're gone ..." should appear. When the user returns to the page, change the message to "Good to be back".

Is it possible to do something like this?

Yor
  • 23
  • 7
  • 3
    Yes. Show us your code, and we will help you – aca Jul 11 '22 at 13:23
  • Well the code it's not much... Just html with some multiple div and css, so is it important that I add it? – Yor Jul 11 '22 at 13:28
  • Does this answer your question? [Javascript to detect if user changes tab](https://stackoverflow.com/questions/10338704/javascript-to-detect-if-user-changes-tab) – mousetail Jul 11 '22 at 13:38

2 Answers2

1

Crate an eventListener on your window, with the load event, and simply show an alert.

And create an event on your window called onbeforeunload (more info about the event), where you show an alert while leaving the page.

Note: onbeforeunload won't work in this snippet, but try putting inside your code.

window.addEventListener('load', (event) =>{

    alert("Looks like you are back");

});

window.onbeforeunload = function() {
          alert("Looks like you want to leave");
      };
aca
  • 1,071
  • 5
  • 15
0

You can achieve this with the Page Visibility API

Answered here

Aditya Singh
  • 40
  • 1
  • 6