首页 文章

Google Chrome Omnibox API - 在输入时自动选择第一个选项

提问于
浏览
13

因此,我正在尝试为Chrome构建一个简单的Omnibox扩展,供个人使用 . 它的工作方式与任何其他Omnibox扩展一样:您输入扩展名关键字并按Tab键,这将提供多功能框的扩展控件 . 然后键入一个短语或诸如此类的东西,并在多功能框下方弹出一个建议列表 . 然后,您可以使用箭头键或鼠标选择建议,然后浏览器导航到与该建议相关联的页面 . 所有这一切都很好 .

但是,我想要它做的是,当我在没有选择建议的情况下按回车时,我希望浏览器转到建议列表中的第一个建议 . 相反,现在发生了什么,我得到这个错误页面:

chrome error page

我在文档中找不到任何答案 . 这就是我的代码现在的样子(在 background.js 中):

chrome.omnibox.onInputChanged.addListener(
    function(text, suggest)
    {
        text = text.replace(" ", "");
        suggest([
            { content: "http://reddit.com/r/" + text, description: "reddit.com/r/" + text },
            { content: "http://imgur.com/r/" + text, description: "imgur.com/r/" + text }
        ]);
    }
);

chrome.omnibox.onInputEntered.addListener(
    function(text)
    {
        chrome.tabs.getSelected(null, function(tab)
        {
            chrome.tabs.update(tab.id, {url: text});
        });
    }
);

chrome.omnibox.setDefaultSuggestion({ description: "visit /r/%s" });

那么在没有选择建议的情况下按下回车时是否有一种设置默认操作的方法?有点像自定义搜索功能默认情况下在Chrome多功能框中有效吗?

1 回答

  • 16

    chrome.omnibox.onInputChanged.addListener() 中,您需要调用 chrome.omnibox.setDefaultSuggestion() .

    因此,当您在多功能框中键入内容时,您必须按下向下箭头,然后 suggest() 任何剩余的建议,如正常 .


    例:

    chrome.omnibox.onInputChanged.addListener(
        function(text, suggest)
        {
            text = text.replace(" ", "");
    
            // Add suggestions to an array
            var suggestions = [];
            suggestions.push({ content: "http://reddit.com/r/" + text, description: "reddit.com/r/" + text });
            suggestions.push({ content: "http://imgur.com/r/" + text, description: "imgur.com/r/" + text });
    
            // Set first suggestion as the default suggestion
            chrome.omnibox.setDefaultSuggestion({description:suggestions[0].description});
    
            // Remove the first suggestion from the array since we just suggested it
            suggestions.shift();
    
            // Suggest the remaining suggestions
            suggest(suggestions);
        }
    );
    
    chrome.omnibox.onInputEntered.addListener(
        function(text)
        {
            chrome.tabs.getSelected(null, function(tab)
            {
                var url;
                if (text.substr(0, 7) == 'http://') {
                    url = text;
    
                // If text does not look like a URL, user probably selected the default suggestion, eg reddit.com for your example
                } else {
                    url = 'http://reddit.com/r/' + text;
                }
                chrome.tabs.update(tab.id, {url: url});
            });
        }
    );
    

相关问题