Chrome Extension - first link is auto-focused in popup

后端 未结 6 1283
感动是毒
感动是毒 2021-02-07 11:18

How do I stop my Google Chrome extension\'s default action to auto-focus the first link in my popup.html? I know I could probably do some roundabout hack with JS o

6条回答
  •  无人及你
    2021-02-07 11:48

    Wrangling the initially focused element with a tabindex attribute is probably the best way to go, using:

    • tabindex="-1", as suggested by Paul Ferret to prevent an element from getting focus
    • tabindex="1", as suggested by link0ff, to specify which element should start with focus

    If your situation is more complicated and you do want to bring in some javascript, I'd recommend using link0ff's solution, except, instead of trying to guess when to blur with timeouts, listen for the initial focus in event:

    function onInitialFocus(event) {
      // Any custom behavior your want to perform when the initial element is focused.
    
      // For example: If this is an anchor tag, remove focus
      if (event.target.tagName == "A") {
        event.target.blur();
      }
    
      // ALSO, remove this event listener after it is triggered,
      // so it's not applied to subsequent focus events
      document.removeEventListener("focusin", onInitialFocus);
    }
    
    // NOTE: the "focusin" event bubbles up to the document,
    // but the "focus" event does not.
    document.addEventListener("focusin", onInitialFocus);
    

    I don't believe the focus event is cancelable, so you can't just suppress the event.

提交回复
热议问题