在Chrome扩展程序中打开新标签页

syn*_*pis 0 javascript jquery json google-chrome-extension

我正在尝试编写一个简单的谷歌扩展程序,点击"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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

这是我的内容.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);
    }
});
Run Code Online (Sandbox Code Playgroud)

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

Dig*_*ane 6

根据Google Chrome内容脚本参考,内容脚本无法使用chrome.tabs(以及其他所有chrome.extension内容).

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

  • 谢谢,我使用了消息传递.它就像一个魅力.我现在可以通过按ctrl + alt + x :)来谷歌选择文本 (2认同)