Safari blur event loop after changing window

2019-05-20 03:29发布

问题:

I want to react to a blur event with a alert box. The idea is to validate the content and give feedback if the the value is not valid. I am not using the alert box for debugging, my client insists on that for giving the user feedback. I had a similar here: (But this question is not redundant!) Focusout event loop

So my current solution looks like this way

HTML:

Type some stuff here:
<br>
<input type="text" id="test" />

JavaScript:

var doFocus = function () {
  $("#test").focus();
    console.log("do focus");
};

$("#test").blur(function () {
  console.log("Blur event got triggered.");
  alert("Blur event got triggered.");
  window.setTimeout(function () {
    doFocus();
  }, 1);
});

This works so far, but the Problem is: if you open the site, click into the input field and then change the window. For example open a text editor, and then change back. The Safari gets stuck in a event loop (the callback is called again and again)...

回答1:

Just remove this line:

alert("Blur event got triggered.");

Alert() should never been used in any blur event callback function.

UPDATE

DEMO

var doFocus = function () {
  $("#test").focus();
    console.log("do focus");
};

var bluring = function(sender){
    $(sender).off('blur');
    console.log("Blur event got triggered.");
    alert("Blur event got triggered.");
    window.setTimeout(function () {
      doFocus();
      $(sender).on('blur',function(){bluring(this)});
    }, 1);
};

$("#test").blur(function(){bluring(this)});


回答2:

I was able to add alert.The safari invokes 'activate' for a new window when still on old window.Added "time out" to enter proper time frame.Making alert conditional and changing the related variables before first alert occurs prevents the alert loop.

Example:

safari.application.addEventListener("activate", function(){
  //setTimeout prevents boundary complications
  setTimeout(
  function() {
    if (enabled) {
      var tab = safari.application.activeBrowserWindow.activeTab;
      if (curTab != tab) {
        curTab = tab;
        if (selectedTab != tab)
        alert('This is an alert!!');

      }
    }
  }
  ,1000);
},true);