2013-10-03 29 views
16

我正在寻找一种方法将选定的文本放入我的Chrome扩展程序中。Chrome扩展程序获取选定文本

我想要前。在Facebook供稿中选择一个文本,当我点击我的图标时,它会得到它并在我的扩展中显示选定的文本。

我得到这个至今:

chrome.tabs.executeScript(null, 
    {code:"alert(window.getSelection().toString());"}) 

它得到选定的文本,并在Chrome的消息提醒它。但是我想在我的html弹出窗口中显示它。我想写出来这样:

document.getElementById("output").value = "Selected text here(but how)" 

需要帮助!我知道还有其他问题,但他们没有给我正是我想要的..

+0

这是我结束了: chrome.tabs.executeScript(NULL,{代码: “window.getSelection()的toString();”}, 功能(结果){ 的document.getElementById(”输出“)。value = results; } 作品! –

回答

26

您可以使用一个被执行的代码最后计算的表达式回拨功能:

chrome.tabs.executeScript({ 
    code: "window.getSelection().toString();" 
}, function(selection) { 
    document.getElementById("output").value = selection[0]; 
}); 
+0

它在同源帧和不同源帧中不起作用。 此外它频繁地返回实际上未选中的文本,因为现在聚焦在不同的帧中。 此外,它不适用于输入字段,但这不是问题: 'code \t let el = activeWindow.document.activeElement; \t如果(isTextElem(EL)){ \t \t如果(在El && el.selectionStart 'selectionStart'!== el.selectionEnd){ \t \t \t回el.value.substring(el.selectionStart,el.selectionEnd ); \t \t} \t} ' – vitaliydev

2

您可以通过使用Extensions Messaging。基本上,您的“后台页面”会将请求发送到您的服务。例如,假设您有一个“弹出式窗口”,一旦您点击它,它会执行“Google搜索”,这是您的服务。

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
    if (request.method == "getSelection") 
     sendResponse({data: window.getSelection().toString()}); 
    else 
     sendResponse({}); // snub them. 
}); 

一些参考

1)Creating a chrome extension which takes highlighted text on the page and inserts it into a textarea in popup.html

或者你可以使用这个插件

2)https://chrome.google.com/webstore/detail/view-selection-source/fbhgckgfljgjkkfngcoeajbgndkeoaaj

+0

这不会发送给我的HTML文档? –