0

I am developing a chrome extension. I am trying to get the selected/highlighted text from the active tab and do something with it. For now, say all the extension does is writing what the selected text is on a popup. I can't seem to do it. I tried a lot of methods. content script, background scripts. Nothing works. in my manifest.jsonI have permissions for activeTab, contextMenus. I tried multiple functions that take the selected text but nothing works. Example of some functions

const text = (window.getSelection) ?
    window.getSelection().toString() :
    document.selection.createRange().text;

console.log(text)

chrome.contextMenus.create({
  id: 'selectionGetter',
  title: 'send selected text',
  contexts: ['selection'],
});

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, 
        function(response){
        
        const url=response.url;
        const subject=response.subject;
          const body = response.body;
          
        console.log(body)
        });
      });
    
      chrome.browserAction.onClicked.addListener(function(tab) {
        chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, 
 function(response){
           sendServiceRequest(response.data);
        });
      });

Would love your help

Contentop
  • 889
  • 1
  • 11
  • 32

1 Answers1

1

See How to access the webpage DOM rather than the extension page DOM? for full explanation, here's a quick illustration:

chrome.tabs.executeScript({code: 'getSelection().toString()'}, ([sel] = []) => {
  if (!chrome.runtime.lastError) {
    document.body.textContent = 'Selection: ' + sel;
  }
});

If you have default_popup declared in manifest.json then put this code in popup.js, and put <script src=popup.js></script> in popup.html. It will run each time the popup is shown.

Otherwise put it inside chrome.browserAction.onClicked listener in the background script.

wOxxOm
  • 43,497
  • 7
  • 75
  • 96