可以't在Chrome扩展上返回所选文本
Can't return selected text on Chrome Extension
我想在按下快捷键时返回所选文本。
这是我的代码:
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的精彩接球。)
- 在HTML表单中键入时返回文本
- 返回文本区域的原始上下文菜单
- 简单的js替换并返回文本
- jquery ajax不会在出现错误时返回文本和/或火警警报
- 如何在ajax中返回文本文件值Asynchronous"Synchronous正在被弃用”;
- 将文本更改为输入并返回文本
- 如何从保留换行符的 window.prompt() 返回文本
- 无法使用 AJAX 获取 url 的 StumbleOn 视图,因为它的 API 返回文本/纯文本
- SVG 子节点返回文本
- 访问选项对象(在 ngSelect 中使用),但仅返回文本框中的特定值
- 如何使用 Ionic 返回文本框的值
- getSelection在清除后返回文本
- JavaScript返回文本+播放声音
- xmlrequest不会从php返回文本
- 为什么ajax调用失败.下面的代码重定向到authenticate.php,而不是返回文本到login.html
- Jquery的val()不会返回文本框的值
- 美元.getJSON失败,但返回文本
- nodeValue不返回文本
- jQuery根据标签标签从span标签返回文本
- 通过HTTP请求返回文本文件作为数组javascript