简体   繁体   中英

How to change tab name in browser when user goes off from my site

So I am making a website and everything is nicely done but I don't know that many things with javascript.

I was searching for something that will help me with this and found some similar things but it doesn't work in my case.

This is the problem/idea:

  • User is on my site and the page name is eg. Hello ( tag) Then the user clicks on the other tab in the browser but doesn't close my website. When that happens my page title changes to eg. You went ? When he clicks on my tab again title changes back to default one.

So if someone can help me with the code and explain it a little bit.

Thank you.

You need to make use of the onblur and onfocus events for the window object.

So something like this (this is native javascript, no jquery).

<script>

window.onblur = function () { document.title = 'you went?'; }

window.onfocus = function () { document.title = 'you came back'; }

</script>
$(window).focus(function() {
   document.title = 'defult title';
});

$(window).blur(function() {
   document.title = 'you went?';
});

You can use :

window.addEventListener('blur',function(){
alert("please Came Back");
 document.head.title = "your tilte"
  });

 window.addEventListener('focus',function(){
 alert("Hi");
 document.head.title = "your tilte"
  });

best for me is use:

window.onload = function() {

  var pageTitle = document.title;
  var attentionMessage = 'Come Back!';

  document.addEventListener('visibilitychange', function(e) {
    var isPageActive = !document.hidden;

    if(!isPageActive){
      document.title = attentionMessage;
    }else {
      document.title = pageTitle;
    }
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM