Monday, May 20, 2024
43
rated 0 times [  45] [ 2]  / answers: 1 / hits: 16245  / 12 Years ago, wed, january 16, 2013, 12:00:00

I have spent several hours searching the web for solutions. What I would like to do is take the highlighted text on a page and transfer it to a textarea in the popup.html of the chrome extension. I was wondering if someone could supply me with suggested source code of an extension that could do this.



This is the most pertinent thread I looked at that i thought would be most helpful - query is similar. Button in popup that get selected text - Chrome extension



I tried copying the code and running it as an extension, it does not obtain the highlighted text. Was wondering if anyone had any suggestions and how to solve this problem. Thank you very much.


More From » google-chrome-extension

 Answers
36

  Well just like the answer to the question you linked, you will need to make use of Message Passing and Content Scripts. That code is over 2 years old though and makes use of depreciated methods such as onRequest and getSelected. A few simple modifications should be plenty to update it to the new api's.



Popup.html



<!DOCTYPE html> 
<html>
<head>
<script src=jquery-1.8.3.min.js></script>
<script src=popup.js></script>
<style>
body { width: 300px; }
textarea { width: 250px; height: 100px;}
</style>
</head>
<body>
<textarea id=text> </textarea>
<button id=paste>Paste Selection</button>
</body>
</html>


popup.js (so as to not have any inline code)



$(function(){
$('#paste').click(function(){pasteSelection();});
});
function pasteSelection() {
chrome.tabs.query({active:true, windowId: chrome.windows.WINDOW_ID_CURRENT},
function(tab) {
chrome.tabs.sendMessage(tab[0].id, {method: getSelection},
function(response){
var text = document.getElementById('text');
text.innerHTML = response.data;
});
});
}


selection.js



chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == getSelection)
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});


manifest.json



{
name: Selected Text,
version: 0.1,
description: Selected Text,
manifest_version: 2,
browser_action: {
default_title: Selected Text,
default_icon: online.png,
default_popup: popup.html
},
permissions: [
tabs,
<all_urls>
],
content_scripts: [
{
matches: [<all_urls>],
js: [selection.js],
run_at: document_start,
all_frames: true
}
]
}


Here is a link to source files.


[#80840] Tuesday, January 15, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devlin

Total Points: 474
Total Questions: 113
Total Answers: 100

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
devlin questions
Tue, Apr 27, 21, 00:00, 3 Years ago
Sat, Oct 31, 20, 00:00, 4 Years ago
Fri, Aug 28, 20, 00:00, 4 Years ago
;