Get selected webpage text in google chrome extension

I am developing a Google Chrome extension. When the popup window was clicked, I would like the input box to be present in the popup.html file to contain the selected text of the current web page.

Example text field:

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

When text is selected on a web page, the text box should contain the selected word. I tried with chrome.extension.getBackgroundPage().getSelection(), but it does not work.

+3
source share
3 answers

There is a stream in google groups: how to get HTML code from a 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 the plugin anyway.

+4

, 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();
+3

, , - Chrome.

chrome.extension.getBackgroundPage().getSelection() , "BackgroundPage" -. - :

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

. , .

+1

Source: https://habr.com/ru/post/1750784/


All Articles