Get the selected text of a web page in google chro

2020-06-06 01:55发布

问题:

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.

回答1:

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.



回答2:

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


回答3:

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.