10

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.

Community
  • 1
  • 1
user1982011
  • 307
  • 1
  • 4
  • 12

3 Answers3

20

  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.

BeardFist
  • 8,031
  • 3
  • 35
  • 40
  • your code is partial and does not work for multiple frames in a page because of `var text = document.getElementById('text'); text.innerHTML = response.data;` in popup.js – Sudarshan Jan 16 '13 at 14:50
  • @Sudarshan I guess you didn't read the question, because all I did was show him what was wrong with the code he linked. – BeardFist Jan 16 '13 at 17:14
  • Hi, thank you very much for putting in so much effort into this! I tried copying your above code and saving it as separate files and then running this as a packed extension but unfortunately it doesn't pull any of the highlighted text, when you ran this did it work fine? Thank you so much again for your help! – user1982011 Jan 18 '13 at 04:01
  • 1
    @user1982011 Yes, it worked for me. Did you make sure to refresh the page before you tried to use it? It needs to inject the script before it can work. – BeardFist Jan 18 '13 at 04:08
  • `"all_frames": true` to deep into all iframes solved my own issue. Thank you! – Carlos May 23 '19 at 13:53
  • I tried the code as is and while the extension popup shows, the Paste Selection button does nothing. (I refreshed the web page first). If I use CTRL-V, it pastes text I manually copied earlier, not my selected text. [I copy/pasted all the code from above, into the correctly named files, etc. No errors but not functioning. Will try the zipped files] – ultrageek Nov 25 '21 at 22:49
  • Actually, I rechecked and there IS an error -- a complaint about the anonymous function in popup.js ("$ is not defined"). And the zipped file is no longer available.This is because jQuery is not loaded if you don't download it yourself. Chrome no longers allow externally-sourced JS, I believe, so don't forget to include download jQuery JS with your other files. You can get it from https://www.cdnpkg.com/jquery/1.8.3 – ultrageek Nov 25 '21 at 22:59
  • One final comment... To summarize, I manually copy/pasted all the code above, downloaded jQuery 1.8.3 min, etc., loaded the unpacked extension and ran on several tabs/ sites. It worked for highlighted text in Facebook, didn't work anywhere else. When I tried it again on FB, it sometimes didn't work. Anyone have any idea why the inconsistency? – ultrageek Nov 26 '21 at 06:23
7

popup.js

chrome.tabs.executeScript( {
  code: "window.getSelection().toString();"
}, function(selection) {
  alert(selection[0]);
});

manifest.json

"permissions": [
    "activeTab",
],

Have a look at this simple extension https://github.com/kelly-apollo/zdic

Kelly Apollo
  • 350
  • 2
  • 14
0

Reference to BeardFist answer below

Aslo, in popup.html you can use CDN version instead :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

And adding this line in the the manifest file :

 "content_security_policy": "script-src 'self' 'unsafe-eval' https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js; object-src 'self'",
Éric F
  • 63
  • 7