Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 485
Aakash Chakravarthy Avatar asked Oct 27 '25 00:10

Aakash Chakravarthy


1 Answers

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.

like image 105
Nick Craver Avatar answered Oct 29 '25 15:10

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!