简体   繁体   English

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

[英]Can't return selected text on Chrome Extension

I would like to return the selected text when pressing a shortcut. 我想在按快捷方式时返回所选的文本。

Here's my code : 这是我的代码:

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

It returns nothing, even if I have currenctly selected text. 即使我当前选择了文本,它也不会返回任何内容。 If I remove toString, here's the output : 如果我删除toString,则输出如下:

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

Any idea about how I could actually return my selection? 关于如何实际返回选择的任何想法?

The listener is added in your background page, so window.getSelection() refers to the text selected in your (automatically generated) background page, not in the active tab. 侦听器已添加到您的背景页面中,因此window.getSelection()引用在(自动生成的)背景页面中选择的文本,而不是在活动选项卡中。 In order to retrieve the selected text from the active tab, you need to inject a little code to do it for you and report back with the result. 为了从活动选项卡中检索选定的文本,您需要注入一些代码来为您完成此操作,然后报告结果。

Eg: 例如:

background.js: 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.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"
        }
    }
}

One more thing to note: 还有一件事要注意:

Accroding to this answer (and my own experience with Chrome v31) the official docs on declaring a keyboard shortcut (aka command) are falsely stating you can set the key-combination programmatically. 对此答案 (以及我对Chrome v31的经验)的认可,是宣告键盘快捷键(即命令)的官方文档 错误地 指出,您可以通过编程方式设置按键组合。
The truth (as "stolen" from the aforementioned answer) is: 真相(如上述答案“被盗”)是:

On Chrome 29 (and later) you have to navigate to chrome://extensions/ and scroll down to the bottom of the page. 在Chrome 29(及更高版本)上,您必须导航至chrome://extensions/并向下滚动至页面底部。 On the right side there is a button Keyboard shortcuts . 在右侧,有一个Keyboard shortcuts按钮。

Modal dialog pops up with all extensions that have registered some commands in their manifest file. 弹出对话框,显示所有在其清单文件中注册了某些命令的扩展名。 But the shortcuts itself are Not set so the user must set them manually. 但是快捷方式本身Not set因此用户必须手动设置它们。

(emphasis mine) (强调我的)

UPDATE: 更新:

The whole truth is this: 整个事实是这样的:

  • If the suggested_key is not already in use as a keyboard shortcut on the user's platform, then the binding works as expected. 如果suggested_key不是已经在使用的键盘快捷键 ,用户的平台上,如预期那么结合的作品。

  • If the suggested_key is already bound to a different command, then the binding is not set up. 如果suggested_key已绑定到其他命令,则不会设置绑定。 The user has to navigate to chrome://extensions/ and click the Keyboard shortcuts button at the bottom of the page. 用户必须导航至chrome://extensions/ ,然后点击页面底部的Keyboard shortcuts按钮。 In the dialog that pops up, the user has to assign a shortcut to the registered command manually. 在弹出的对话框中,用户必须手动为注册的命令分配快捷方式。

  • While testing, after changing the suggested_key in manifest, you need to uninstall and re-install the extension for the changes to take effect. 测试时,改变后suggested_key清单中,您需要卸载并重新安装扩展,以使更改生效。 Simply reloading or disabling and re-enabling the extension won't work. 简单地重新加载或禁用并重新启用扩展将不起作用。 (Thx to rsanchez for this nice catch.) 感谢rsanchez抓住这个好机会。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM