如何避免将焦点移动到Chrome扩展中的谷歌搜索栏
How can I avoid having the focus moved to the Google search bar in a Chrome extension?
我正在为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"
}
]
}
相关文章:
- 如何在谷歌开发者控制台上为firefox扩展创建oAuth项目
- 如何知道你右键点击谷歌chrome扩展是什么
- 对齐底部的DIV-谷歌Chrome扩展
- 谷歌扩展:如何在弹出窗口中按下按钮时在我的javascript文件中运行函数
- 列出谷歌浏览器中安装的所有扩展程序
- 浏览器扩展程序来跟踪我的谷歌活动
- 谷歌浏览器扩展程序画布图标
- 为什么我的谷歌浏览器扩展程序在谷歌浏览器版本 41.0.2272.89 中不起作用
- 如何缩小我的谷歌chrome扩展's的javascript文件
- 当弹出窗口关闭时播放声音文件(谷歌扩展)
- 谷歌Chrome扩展在用Javascript打开的弹出窗口中工作吗
- 基本的谷歌chrome扩展消息传递不起作用
- 按钮点击不工作在谷歌扩展
- AngularJS-谷歌Chrome扩展中的动态链接断开
- 谷歌浏览器扩展程序 - 获取字符串中的选项卡内容
- 如何扩展谷歌应用程序脚本类
- 如何写自定义扩展谷歌地图在一个干净的方式
- 连接并扩展谷歌地图上的多边形编辑功能
- 扩展谷歌地图api类(或制作包装器)
- 扩展谷歌地图标记动画顺利更新