无法在Chrome扩展程序上返回所选文字

时间:2013-12-16 09:16:05

标签: javascript google-chrome google-chrome-extension selection

我想在按快捷键时返回所选文字。

这是我的代码:

chrome.commands.onCommand.addListener(function(command) {
    console.log(window.getSelection().toString());
});

即使我当前选择了文本,它也不会返回任何内容。 如果我删除toString,这是输出:

anchorNode: null
anchorOffset: 0
baseNode: null
baseOffset: 0
extentNode: null
extentOffset: 0
focusNode: null
focusOffset: 0
isCollapsed: true
rangeCount: 0
type: "None"

关于如何实际返回我的选择的任何想法?

1 个答案:

答案 0 :(得分:4)

监听器已添加到您的后台页面中,因此window.getSelection()指的是在(自动生成的)背景页面中选择的文本,而不是活动选项卡中的文本。 为了从活动选项卡中检索所选文本,您需要注入一些代码来为您执行此操作并报告结果。

E.g:

<强> background.js:

/* The function that finds and returns the selected text */
var funcToInject = function() {
    var selection = window.getSelection();
    return (selection.rangeCount > 0) ? selection.toString() : '';
};

/* This line converts the above function to string
 * (and makes sure it will be called instantly) */
var jsCodeStr = ';(' + funcToInject + ')();';

chrome.commands.onCommand.addListener(function(cmd) {
    if (cmd === 'selectedText') {
        /* Inject the code into all frames of the active tab */
        chrome.tabs.executeScript({
            code: jsCodeStr,
            allFrames: true   //  <-- inject into all frames, as the selection 
                              //      might be in an iframe, not the main page
        }, function(selectedTextPerFrame) {
            if (chrome.runtime.lastError) {
                /* Report any error */
                alert('ERROR:\n' + chrome.runtime.lastError.message);
            } else if ((selectedTextPerFrame.length > 0)
                    && (typeof(selectedTextPerFrame[0]) === 'string')) {
                /* The results are as expected */
                alert('Selected text: ' + selectedTextPerFrame[0]);
            }
        });
    }
});

<强> 的manifest.json:

{
    "manifest_version": 2,

    "name":    "Test Extension",
    "version": "0.0",

    "background": {
        "persistent": false,
        "scripts": ["background.js"]
    },

    "permissions": ["<all_urls>"],

    "commands": {
        "selectedText": {
            "description": "Retrieve the selected text in the active tab"
        }
    }
}

还有一点需要注意:

累积到 this answer (以及我自己使用Chrome v31的经验)声明键盘快捷键(也就是命令)的官方文档是 falsely 说明您可以通过编程方式设置组合键 事实(从上述答案中“被盗”)是:

在Chrome 29(及更高版本)上,您必须导航至chrome://extensions/并向下滚动到页面底部。在右侧有一个按钮Keyboard shortcuts

弹出模式对话框,其中包含已在其清单文件中注册了某些命令的所有扩展名。但快捷方式本身为Not set,因此用户必须手动设置它们。

(强调我的)

<强>更新

事实是:

  • 如果suggested_key 已在用户平台上用作 keyboard shortcut ,则绑定按预期工作

  • 如果suggested_key已绑定到其他命令,则不会设置绑定。用户必须导航至chrome://extensions/,然后点击页面底部的Keyboard shortcuts按钮。在弹出的对话框中,用户必须手动为注册的命令分配快捷方式。

  • 在测试时,在更改清单中的suggested_key后,您需要卸载并重新安装扩展程序才能使更改生效。只需重新加载或禁用并重新启用扩展程序将无效。 (感谢 rsanchez 这个很好的捕获。)