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

Gas*_*ard 1 javascript google-chrome selection google-chrome-extension

我想在按快捷方式时返回所选的文本。

这是我的代码:

chrome.commands.onCommand.addListener(function(command) {
    console.log(window.getSelection().toString());
});
Run Code Online (Sandbox Code Playgroud)

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

anchorNode: null
anchorOffset: 0
baseNode: null
baseOffset: 0
extentNode: null
extentOffset: 0
focusNode: null
focusOffset: 0
isCollapsed: true
rangeCount: 0
type: "None"
Run Code Online (Sandbox Code Playgroud)

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

gka*_*pak 5

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

例如:

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]);
            }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

还有一件事要注意:

Accroding到这个答案(和我自己的Chrome V31经验)上宣布键盘快捷键(又名命令)官方的文档错误地指出您可以编程设定的组合键。
真相(如上述答案“被盗”)是:

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

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

(强调我的)

更新:

整个事实是这样的:

  • 如果suggested_key不是已经在使用的键盘快捷键,用户的平台上,如预期那么结合的作品。

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

  • 在测试过程中,更改suggested_key清单后,您需要卸载并重新安装扩展名,以使更改生效。简单地重新加载或禁用并重新启用扩展将不起作用。(感谢rsanchez抓住这个好机会。)