我正在开发谷歌浏览器扩展。当点击弹出窗口时,我希望popup.html文件中的输入框包含当前网页的选定文本。获取谷歌Chrome扩展的网页选定文本
实施例的文本框:
<input id="searchBox" type="text" />
当文本在网页中被选择时,文本框应包含所选择的字。我尝试使用chrome.extension.getBackgroundPage().getSelection()
,但它不起作用。
我正在开发谷歌浏览器扩展。当点击弹出窗口时,我希望popup.html文件中的输入框包含当前网页的选定文本。获取谷歌Chrome扩展的网页选定文本
实施例的文本框:
<input id="searchBox" type="text" />
当文本在网页中被选择时,文本框应包含所选择的字。我尝试使用chrome.extension.getBackgroundPage().getSelection()
,但它不起作用。
有关于这个对谷歌组线程:how to get HTML code from selection?
var selection = window.getSelection();
var range = selection.getRangeAt(0);
if (range) {
var div = document.createElement('div');
div.appendChild(range.cloneContents());
alert(div.innerHTML);
}
您可以在控制台或插件,无论哪种方式,用这个。
你试图做的事情需要很多编码,因为Chrome的极端安全防范措施。
chrome.extension.getBackgroundPage().getSelection()
将不起作用,因为“BackgroundPage”不是当前网页。你需要这样的东西:
chrome.tabs.executeScript(null, {code:"alert(window.getSelection().toString());"})
//alerts the selected text
但是,将该文本转移回弹出是一个长期和偏头痛的过程。如果您有挑战,请阅读 Contentscripts and Extension Messaging。
这里是让所选择的字符串形式的文字另一个简单的解决方案,你可以很容易地使用这个字符串的div元素孩子添加到您的代码:
var text = '';
if(window.getSelection){
text = window.getSelection();
}else if(document.getSelection){
text = document.getSelection();
}else if(document.selection){
text = document.selection.createRange().text;
}
text=text.toString();
但这个插件https://开头chrome.google.com/extensions/detail/fbhgckgfljgjkkfngcoeajbgndkeoaaj获取选择来源。 – 2010-06-19 07:09:32
是的。它使用了我向你展示的同样的东西。 继承人的脚本: 'chrome.tabs.executeScript(NULL,{文件: “的script.js”});' 和: 'chrome.extension.onRequest.addListener( 函数(请求,发件人,第一部分基本上是我向你展示的代码(除了在脚本文件中),第二部分是第二部分是代码消息。 – tcooc 2010-06-19 16:58:09