在Chrome扩展中打开新选项卡

Open new tab in Chrome extensions

本文关键字:选项 新选项 Chrome 扩展      更新时间:2023-09-26

我正在尝试编写一个简单的谷歌扩展,点击"ctrl+alt+x"即可在谷歌中搜索所选文本。

这是我的主要节日:

{
  "name": "A jQuery Chrome extension",
  "version": "0.1",
  "description": "Use jQuery to build Chrome extensions",
  "content_scripts": [
    {
        "matches" : ["http://*/*"],
      "js": ["jquery.js", "jquery.hotkeys.js", "content.js"]
    }
  ],
  "background_page": "background.html",
  "permissions": [
    "tabs"
  ]
}

这是我的内容.js:

$(document).bind('keydown', 'alt+ctrl+x', function() {
    var selectedText = window.getSelection().toString();
    if (selectedText)
    {
        var googleQuery = "http://www.google.com/search?q=" + selectedText;
        alert(googleQuery);
        chrome.tabs.create({"url" : googleQuery});  
        alert(googleQuery);
    }
});

代码一直工作到打开新选项卡的行(第一个警报弹出,但第二个没有弹出)。我似乎就是不能让它工作。我错过了什么?

根据Google Chrome内容脚本参考,chrome.tabs(以及除chrome.extension之外的所有内容)不可用于内容脚本。

作为替代方案,您可以尝试window.open(),或者使用消息传递让您的后台页面打开选项卡。