如何避免将焦点移动到Chrome扩展中的谷歌搜索栏

How can I avoid having the focus moved to the Google search bar in a Chrome extension?

本文关键字:扩展 谷歌 搜索栏 Chrome 何避免 焦点 移动      更新时间:2023-09-26

我正在为Chrome编写一个扩展,其中包含了一些我发现在Firefox vimperator插件中最有用的功能。

目前我有一些麻烦捕获击键之前的网页做。"easiest"以"google.com"为例。当我在搜索字段中键入一些没有焦点的内容时,该字段将被自动选中,并且我输入的任何文本都将被输入到该字段中。

本质上,我想停止这种行为,这样当我按下按钮时,焦点就不会移动到搜索字段。(在那之后,我希望扩展根据按下的键作出反应,但我已经或多或少地工作了,如果我能阻止焦点被移动。)

到目前为止,我已经尝试了各种组合的removeEventListener()和jQuery unbind()和其他一些东西(或疯狂的猜测,如果你喜欢)在我的扩展的内容脚本,但没有运气到目前为止。当按下字母数字键时,焦点仍然移动到搜索字段。有没有人对如何做到这一点有任何建议,或者我可以在哪里找到答案?

我很抱歉以前有人问过这个问题,但是我无法从我发现的任何问题中得到任何帮助。

PS:如果你应该对更多的上下文感兴趣,我到目前为止的代码可以在这里找到。但我认为这个问题是可以回答的,没有人会因为看到这个(混乱)而感到头痛。

在阅读了element.focus()方法之后,我编写了以下代码来模糊在focus()调用返回事件循环之前文档关注的元素。

我们的想法是,我们添加一个焦点监听器到每个元素,然后在onload后删除焦点监听器,以便在用户事件后调用focus()的网站(如jsfiddle.com或Google结果页面)在页面加载后仍将正常工作。

警告:我还没能弄清楚如何让Chrome禁用autofocus字段。

内容脚本(命名为unfocus.js):

document.addEventListener('DOMNodeInsertedIntoDocument', onInsertedIntoDocument, true);
document.addEventListener('DOMNodeRemovedFromDocument', onRemovedFromDocument, true);
window.addEventListener('load', function(e) {
  setTimeout(function() {
    removeOnFocus(document.documentElement);
    document.removeEventListener('DOMNodeInsertedIntoDocument', onInsertedIntoDocument, true);
    document.removeEventListener('DOMNodeRemovedFromDocument', onRemovedFromDocument, true);
  }, 1);
}, false);

// Whenever an element is inserted into document, listen for
// simple event named 'focus'.
function onInsertedIntoDocument(e) {
  var elt = e.target;
  if (elt.nodeType === 1)
    elt.addEventListener('focus', onfocus, false);
}
function onRemovedFromDocument(e) {
  var elt = e.target;
  if (elt.nodeType === 1)
      removeOnFocus(elt);
}
function onfocus(e) {
  // In Chrome, caller is null if the user initiated the focus,
  // and non-null if the focus was caused by a call to element.focus().
  var causedByUser = (onfocus.caller == null);
  console.log('onfocus ' + e.target.nodeName +
      ': caused by user? ' +causedByUser +
      (e.target.autofocus ? ' autofocus' : ''));
  if (! causedByUser) {
    e.target.blur();
  }
}
// Clean up by removing all the 'focus' event listeners.
function removeOnFocus(elt) {
  elt.removeEventListener('focus', onfocus, false);
  for (var i = 0; i < elt.children.length; i++)
    removeOnFocus(elt.children[i]);
}

和manifest.json:

{
  "name": "unfocus",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["unfocus.js"],
      "run_at": "document_start"
    }
  ]
}