在Google Chrome扩展程序中获取网页的选定文本 [英] Get the selected text of a web page in google chrome extension

查看:909
本文介绍了在Google Chrome扩展程序中获取网页的选定文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Google Chrome扩展程序。点击弹出窗口时,我希望popup.html文件中的输入框包含当前网页的选定文本。



示例文本框:

 < input id =searchBoxtype =text/> 

在网页中选择文本时,文本框应该包含选定的单词。我尝试过使用 chrome.extension.getBackgroundPage()。getSelection()但它不起作用。

解决方案

谷歌组织上有一条关于此的帖子:如何从选择中获取HTML代码?

  var selection = window.getSelection() ; 
var range = selection.getRangeAt(0);
if(range){
var div = document.createElement('div');
div.appendChild(range.cloneContents());
alert(div.innerHTML);
}

无论哪种方式,您都可以在控制台或插件中使用它。 / p>

I am developing a Google Chrome extension. When a popup is clicked, I would like the input box present in the popup.html file to contain the selected text of the current webpage.

Example textbox:

<input id="searchBox" type="text" />

When text is selected in a webpage, the textbox should contain the selected word. I tried with chrome.extension.getBackgroundPage().getSelection() but it is not working.

解决方案

There was a thread about this on google groups: 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); 
}

You can use this in the console or in a plugin, either way.

这篇关于在Google Chrome扩展程序中获取网页的选定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆