简体   繁体   中英

Why does jquery focus() fire only once?

I have a Chrome Extension that adds an iframe to specific URLs.

I created a shortcut key to move focus to an input box in the iFrame.

The content script sends a message to background, which messages the iframe.

It works great - once.

  • The console message in the code below (which is the in the iframe js file) always fires - so I know the message is getting through
  • If I change the code to insert a value into the input it works every time
  • I added $('#searchLibraryTB').blur(); to the success handler for the input box...this seems to clear things out and subsequent messages to focus on the input will work. It is only if you focus on the input, then mouse away (without entering anything and triggering the success handler) that the focus does not work. Through a little trial and error I think the issue is that I set the focus once, and the iframe thinks the element STILL has focus - even after I've clicked back into the main window. So this path works because I programmatically blur away from the input. So the solution has to do something to clear/remove the focus set from the first iteration.
    • I have an "on focus clear any value' line in the iframe JS file and, while the cursor doesn't stay in the input when the message comes through it does clear out any text in the input, implying something is getting through.

I've read some old threads about focus() only working once on Chrome...I can't believe that to be true. I think it's due to some sort of event doubling or something...

Any ideas?

Here is the message receiver in the iframe JS. Again, this ALWAYS receives the message to place focus on the input. It just doesn't do it after the first call. Refreshing the page resets things and the messaging will work once.

Thank you!

  chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
    if (request.method === "focusToolbar"){
      console.log('Receiving message from background to focus toolbar in aSearch.js...');
      // $('#searchLibraryTB').on("focus", function(){
      //   console.log('search already had focus...');
      //   // $('#searchLibraryTB').val("this sux");
      //   $('#searchLibraryTB').off( "focus" );
      //   // $('#searchLibraryTB').focus();
      // });

      $('#searchLibraryTB').focus();
    }
  });

Sometimes writing out your problem in StackOverflow helps you think through it...

I added a blur event before the focus...to make sure the element does NOT have focus on second and subsequent messaging...

This did the trick.

  $('#searchLibraryTB').blur();
  $('#searchLibraryTB').focus();

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