可以't在Chrome扩展上返回所选文本

Can't return selected text on Chrome Extension

本文关键字:返回 文本 扩展 Chrome 可以      更新时间:2023-09-26

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

这是我的代码:

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"

你知道我如何才能真正返回我的选择吗?

侦听器添加在后台页面中,因此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]);
            }
        });
    }
});

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"
        }
    }
}

还有一点需要注意:

根据这个答案(以及我自己使用Chrome v31的经验),关于声明键盘快捷键(也称为命令)的官方文档是错误地,声明您可以通过编程设置组合键
事实(从上述答案中"被盗")是:

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

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

(强调矿)

更新:

事实是:

  • 如果suggested_key,而不是已在用户平台上用作键盘快捷键,则绑定工作正常。

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

  • 在测试时,更改清单中的suggested_key后,您需要卸载并重新安装扩展才能使更改生效。简单地重新加载或禁用并重新启用扩展是行不通的。(感谢rsanchez的精彩接球。)