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.

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.


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.


Need Your Help

How to send a file on cross-domain with XMLHttpRequest?

javascript ajax xmlhttprequest cross-domain

I'm trying to send a file on another domain but progress event isn't working. If I comment onprogress function, the file is well uploaded, else an error occurs :

jQuery targeting correct radio button is unresponsive

javascript jquery html radio-button

I have a javascript array containing the name and values of radios I want checked.