1

I am checking that the current tab/window is focused or not to perform some particular task.The following function is correctly working to detect the focus when i am switching tabs but when the tab is open and i open a software(music player/windows folders) keeping the tab active/open, the function still consider the window/tab as focused!The situation that i am trying to achieve is to detect that the window/tab is lost the focus due to opening application/software upon currently focused window/tab.It will be great if you provide a jsfiddle with your answer based on my code!

$(document).ready(function() {

        var hidden, change, vis = {
            hidden: "visibilitychange",
            mozHidden: "mozvisibilitychange",
            webkitHidden: "webkitvisibilitychange",
            msHidden: "msvisibilitychange",
            oHidden: "ovisibilitychange" /* not currently supported */
        };             
    for (hidden in vis) {
        if (vis.hasOwnProperty(hidden) && hidden in document) {
            change = vis[hidden];
            break;
        }
    }
    if (change)
        document.addEventListener(change, onchange);
    else if (/*@cc_on!@*/false) // IE 9 and lower
        document.onfocusin = document.onfocusout = onchange
    else
        window.onfocus = window.onblur = onchange;

    function onchange (evt) {
        evt = evt || window.event;
        if (evt.type == "focus" || evt.type == "focusin")
           window_focus = true;
        else if (evt.type == "blur" || evt.type == "focusout")
           window_focus = false;
        else        
           window_focus = this[hidden] ? false : true;
    }

});

Frame:

<frameset rows="130,*" style="border: 1px #CC3333"  noresize="noresize" ">
<frame name="showcountframe" src="https://jsfiddle.net/nvobhaor/1/" scrolling=no marginheight="2" marginwidth="2"  noresize="noresize">
<frame name="showcontframe" src="showcontframe.html" marginheight="0" marginwidth="0" noresize="noresize">
</frameset><noframes></noframes>
query
  • 531
  • 3
  • 7
  • 30
  • Well that's how the `visibilitychange` event works. File a bug or implementation suggestion. As of now the only thing I can think of is visible check for being idle when `document.hidden` is false – Edwin Reynoso Apr 18 '15 at 17:39

1 Answers1

1

You could use window.onfocus and window.onblur for this instead of that wall of code. It is supported by all the main browsers and works perfectly fine for the purpose you want. It detects when you change tabs, for example, or open another application as you said.

Example:

window.onfocus = function() {
    console.log('Focused');
};

window.onblur = function() {
    console.log('Not focused');
};
Igor Antun
  • 116
  • 1
  • 2
  • 14
  • What's about browser compatibility? – query Apr 18 '15 at 19:01
  • It should work everywhere. (confirmed on http://jscc.info/ and seen on http://www.w3schools.com/jsref/event_onfocus.asp) – Igor Antun Apr 18 '15 at 19:14
  • what to do if i want to merge this code with my one ?Should i add like this else if (evt.type == "onblur" ) window_focus = false; ? – query Apr 18 '15 at 19:24
  • You could simply use the code I posted above, using `window_focus = true;` instead of `console.log('Focused');` and `window_focus = false;` instead of `console.log('Not focused');` – Igor Antun Apr 18 '15 at 19:57
  • Individually working!But not working when merging with my code! – query Apr 21 '15 at 21:41
  • Can you provide me a Pastebin or something with your current code? – Igor Antun Apr 21 '15 at 22:56
  • @query that should work: https://jsfiddle.net/nvobhaor/1/ - You were mixing up codes. – Igor Antun Apr 23 '15 at 00:32
  • Can you provide me any solution based on my above code without switching to new one ? I am having difficulties to implement your code in my script so it would be better for me if you can provide a solution modifying my code instead of providing a new one! – query Apr 27 '15 at 22:14
  • All I did was move the variables so they are created globally and therefore accessible inside the other functions' scope, and remove the redundant code you were using to detect the focus change. – Igor Antun Apr 28 '15 at 00:05
  • I know your code is correct to attain my goal but i am curious that can we gain the desired functionality by doing a simple modification in my code ?just like adding "else if (evt.type == "onblur") window_focus = false; " or something else which will make the current code functionable ! – query Apr 28 '15 at 00:26
  • Yeah I could create the window_focus variable as false, so it is already defined to not focused, until you focus the result area. Updated JSFiddle: https://jsfiddle.net/nvobhaor/2/ – Igor Antun Apr 28 '15 at 00:41
  • This is not going to be a worthy solution for me as now i have to say the user to start the timer by resume button!If you have an account you can see the example of my desired functionality here http://www.clixsense.com/en/View_Ads – query Apr 28 '15 at 00:47
  • Ok. But I think this question has gone a bit too far, the original question was 'How to detect the window focus', and for that I gave an answer above... The purpose of StackOverflow is not for us to just do the whole project for anyone. If this answer solved the question, consider accepting it as accepted answer. – Igor Antun Apr 28 '15 at 02:28
  • From the very first i was looking a solution based on my code(hopefully you saw this in my description of the problem ) .The conversation becomes very long as i am not getting the desired solution but i had no intention to get the whole project done by you!however thanks for your hard effort and time on my question! – query Apr 28 '15 at 21:12
  • No problem, you're more than welcome, it's just that I think the final answer was getting a bit too specific, and may not help other people who are just having trouble trying to detect the window focus :) – Igor Antun Apr 29 '15 at 00:10
  • Did that answer solve the question though? You accepted the other answer but I'm not sure if that one solved as well. – Igor Antun Apr 29 '15 at 23:26
  • The answer did not solve the problem rather arises some new problem.Actually i'm running timer inside a frame so when i used your code i had to click the frame portion to fire the onblur moreover onblur marking any click outside that particular frame as a focus lose even though i was clicking just another frame on the same window. – query Apr 29 '15 at 23:41
  • Oh, I see, but as I've said, that's an issue with JSFiddle, it'll work properly on any other page. That's because JSFiddle loads the HTML/JS only on that section, and therefore the code thinks that this section is the whole window. That would happen as well with any other focus detection code. It can happen as well if you're loading the script on an – Igor Antun Apr 29 '15 at 23:45
  • I would like to provide you an example click here http://useclix.com/cks.php?k=789EDCDDB04EDF26F62D2456723CE5A9 and look below that a progress bar is running when you are focusing if you switch tab or launch an application the progress bar will stop (you don't need any click to fire the onblur here) . – query Apr 29 '15 at 23:53
  • But that is working on the JSFiddle, the only difference is that JSFiddle requires you to treat the result section as the whole window. Example: https://igorantun.com/so_query.html - notice how it's working properly, the resume button just shows up when you switch tabs, you don't have to do any prior clicks to focus the window. – Igor Antun Apr 30 '15 at 00:09
  • Probably i am unable to realize you actually what the problem i am facing ! ya i know in jsfiddle i have to click to trigger onblur and in normal page it will work like a charm .But the only thing making the difference is the frame .i have updated my question look above! – query Apr 30 '15 at 00:18
  • Oh, sorry for that. It seems like the most effective way to check that is using something like https://github.com/serkanyersen/ifvisible.js - I updated the JSFiddle: http://jsfiddle.net/nvobhaor/18/ and it now works perfectly for your purpose. – Igor Antun Apr 30 '15 at 00:54
  • have you found the blur working when launching a software ?in my case it is now working like my above code which can only detect the tab switching nothing else.I have seen your updated code in your website but you are using iframe which is not in my case i am using just frame inside a frameset. – query Apr 30 '15 at 01:07
  • Have you observed one interesting thing in your demo ?when you click inside the iframe content the window loses the focus and show the resume button though you are active !!https://igorantun.com/so_query.html – query May 02 '15 at 01:23
  • I'm afraid what you want cannot be done easily... Maybe you should consider just using the first script (in the answer) outside the frame instead so it works properly, if that isn't too complicated for your project. – Igor Antun May 02 '15 at 02:42
  • frame is making the simple thing complex for my project and probably there need some extra magic to make it workable!However,thanks for your patience since the starting of the question and i have marked the answer as accepted to value your hard work :) – query May 02 '15 at 14:09
  • this code works in desktop and also ios safari – Nick Chan Abdullah Oct 04 '21 at 05:59