简体   繁体   中英

javascript onblur / onfocus with iframe not working issues

I use onblur and onfocus function in my page. But also, I use a iframe into page. And my problem is onblur and andfocus functions not working together into page if I use a iframe.

I clicked in iframe when onblur function is working.But I dont want this function work if I clicked in iframe. I want to run only work it if user will change browser tab

if I will use hasFocus function and users changes browser tab , this time onblur is not working

my js codes:

 var after_title = 'Back to page'; var dafault_title = document.title; var deg; window.onblur = function () { document.title = after_title; beep(); deg=setTimeout(check,2000); } window.onfocus = ()=>(deg)?clearTimeout(deg):null; function beep() { var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYU="); snd.play(); } function check() { if(document.hasFocus()){ document.title = dafault_title; return; }else{ location.href = './index.php'; } }
 <html> <head> <title>Demo Page</title> </head> <body> <br><br><br>default page<br><br><br> <br><br><br><br> <iframe id="abc" name="abc" frameborder="1" marginwidth="0" marginheight="0" framespacing="0" width="100px" height="100px"> <p>example include page</p> </iframe> </body> </html>

In order to react to tabchange, don't use the blur and focus events, but rather the Page Visibility API instead:

function handleVisibilityChange() {
  if (document.hidden) { // equivalent to "blur"
    document.title = after_title; beep(); deg=setTimeout(check,2000);
  } else  { // equivalent to "focus"
    if (deg) {
      clearTimeout(deg);
    }
  }
}

document.addEventListener("visibilitychange", handleVisibilityChange, false);

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