views:

62

answers:

2

Hello,

I am on google extension development, when a popup is clicked, the input box present in the popup.html file should contain the selected text of the current webpage.

example textbox,

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

when a 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.

Please help

+1  A: 

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.

digitalFresh
but this plugin https://chrome.google.com/extensions/detail/fbhgckgfljgjkkfngcoeajbgndkeoaaj gets the selection source.
Aakash Chakravarthy
Yes. It used the same thing i showed you.Heres the script: `chrome.tabs.executeScript(null, {file:"script.js"});`And: `chrome.extension.onRequest.addListener( function(request, sender, sendResponse) { document.getElementById("txtar").innerText=request.viewsource; });`The first part is basically the code i showed you(except in a script file), and the second part is the messaging.
digitalFresh
A: 

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.

Nick Craver