0

I was wondering what is the easiest way to get selected text from tab and put string into a variable

My Popup html code

    <!DOCTYPE html>
<html>
    <head>

    </head>

    <body>
          <button id="clickme">click me</button>
        <canvas id="myCanvas" width="300" height="300"></canvas>
          <textarea id="output"> </textarea>
        <script src = "popup.js"></script>
    </body>

</html>

My javaScript

    chrome.tabs.executeScript( {
  code: "window.getSelection().toString();"
}, function(selection) {
  document.getElementById("output").value = selection[0];
});

I tried this but got an error

*

Error in response to tabs.executeScript: TypeError: Cannot read property '0' of undefined at Object.callback (chrome-extension://nnhcblfafgjjoolcnjckidjgjcmmgnlp/popup.js:4:54) at chrome-extension://nnhcblfafgjjoolcnjckidjgjcmmgnlp/popup.js:1:13

*

Yusof Bandar
  • 169
  • 1
  • 4
  • 9
  • 1
    perhaps you need to check if `selection` is not `undefined` before blindly using `selection[0]` – Jaromanda X Mar 11 '17 at 01:53
  • oh so i need to make a selection array, do you know how to – Yusof Bandar Mar 11 '17 at 01:57
  • no idea, you need to check what selection is before blindly assuming it's what you want it to be - I don't even know if your code is valid, because you've posted so little – Jaromanda X Mar 11 '17 at 01:58
  • I was more asking if anyone has some simple code that gets selected text in javascript – Yusof Bandar Mar 11 '17 at 01:59
  • fair enough, I was merely pointing out the flaw in your code – Jaromanda X Mar 11 '17 at 01:59
  • I assume the javascript is in background.js? – Unlocked Mar 11 '17 at 02:22
  • Are you trying to get the content selected on the tab and add it to the textarea on the popup? If yes, you would need messaging passing from popup to frontend and so forth. Let me know and I can provide code. – nitobuendia Mar 11 '17 at 05:22
  • The code is correct, just add a check for undefined. Make sure your manifest.json contains correct permissions. And don't try to run the code on built-in chrome:// or chrome-extension:// pages. – wOxxOm Mar 11 '17 at 08:01

0 Answers0