0

Is there any way to detect previous tabs in Javascript? I'm making a Chrome Extension in which whenever I change the tab it should detect. Whenever I go to or open new tab it detects but when I go back to the previous tab, it doesn't detect.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Shashi Bharti
  • 53
  • 2
  • 6

1 Answers1

0

It's not exactly what you request, but it does most of what you need, I think.

It detects when the the window gets focused/blured, so when a client clicks on another application, other tab, or clicks on the windows desktop, ... that is a blur. One click back in your website is detected as a focus.

Losely based on this How can I detect when the mouse leaves the window?

happy with this?

Maybe add a addEvent(document, "mouseover", ...), and addEvent(document, "mouseout", ...), that combination might give you what you need.

<html>
<head>
<script type="text/javascript">
  // just a function to display a message
  function displayMessage(msg) {
    document.getElementById('message').innerHTML = msg;
  }
  function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
      obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
      obj.attachEvent("on" + evt, fn);
    }
  }
  addEvent(window,"load",function(e) {
    // activate window
    addEvent(window, "focus", function(e) {
      e = e ? e : window.event;
      var from = e.relatedTarget || e.toElement;
      if (!from || from.nodeName == "HTML") {
        // stop your drag event here
        displayMessage('focus'); 
      }
    });
    // blur window
    addEvent(window, "blur", function(e) {
      e = e ? e : window.event;
      var from = e.relatedTarget || e.toElement;
      if (!from || from.nodeName == "HTML") {
        // stop your drag event here
        displayMessage('blur'); 
      }
    });
  });
</script>
</head>
<body>
  <div id="message"></div>
</body>
</html>
Community
  • 1
  • 1
Emmanuel Delay
  • 3,619
  • 1
  • 11
  • 17