【发布时间】:2011-02-07 06:49:49
【问题描述】:
对于 Google Chrome 扩展,我需要在网页中捕获选定的文本并发送到网络服务。我被困住了!
首先我尝试了一个书签,但 Mac 上的 Chrome 似乎有一些书签错误,所以我决定编写一个扩展程序。
我在我的分机中使用此代码:
function getSelText(){
var txt = 'nothing';
if (window.getSelection){
txt = "1" + window.getSelection();
} else if (document.getSelection) {
txt = "2" + document.getSelection();
} else if (document.selection) {
txt = "3" + document.selection.createRange().text;
} else txt = "wtf";
return txt;
}
var selection = getSelText();
alert("selection = " + selection);
当我点击我的扩展程序图标时,我得到一个“1”。所以我认为在浏览器窗口之外选择的行为导致浏览器不再将文本视为“已选择”。
只是一个理论......
想法?
【问题讨论】:
-
不需要使用那种代码。 Chrome 扩展程序只能在 Chrome 中运行,因此只需对其进行优化以在 Chrome 上运行,而不需要复杂的跨浏览器内容。您必须执行 window.getSelection().toString() 才能获取选定的文本。
-
Chrome 扩展程序可以定义一个上下文菜单选项,该选项仅在选择某些文本时显示。 API 提供了一个返回所选文本的属性:请参阅
chrome.contextMenus文档和/或 this answer。
标签: google-chrome google-chrome-extension