Get the selected text of a web page in google chrome extension

孤街浪徒 提交于 2019-12-03 17:22:07

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.

here is another simple solution to get the selected the text in the form of string, you can use this string easily to append a div element child into your code:

              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();

What youre trying to do requires quite a bit of coding because of Chrome's extreme security precautions.

chrome.extension.getBackgroundPage().getSelection() will not work because the "BackgroundPage" is not the current webpage. You need something like:

chrome.tabs.executeScript(null, {code:"alert(window.getSelection().toString());"})
//alerts the selected text

However, to transfer that text back to the popup is a long and migraine-causing process. Read Contentscripts and Extension Messaging if youre up for the challenge.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!