1

I'm making chrome extension to access to webpage DOM as Grammarly like when the user clicks on the word I want to store it, I wrote some code on the content script, but it only works when I click on the extension popup.

enter image description here

My code content script:

chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  const console = {
    log: (info) => chrome.extension.getBackgroundPage().console.log(info),
  };
  chrome.tabs.executeScript(
    tabs[0].id,
    {
      code: "window.getSelection().toString();",
    },
    (result) => {
      console.log(result);
    }
  );
});

as you see when I open the extension popup it then shows the selected word, so my question is how can I get the word as clicking without opening the popup like Grammarly.

Ericgit
  • 6,089
  • 2
  • 42
  • 53
  • 3
    I believe that you need to inject a script to the page itself so it will run as part of the page lifecycle and not as the icon click handler. See this answer: https://stackoverflow.com/a/9517879/863110 – Mosh Feu Jul 26 '20 at 08:51
  • Your script is not a content script because content scripts can't use `chrome.tabs` API. I guess you're using the same script in two places: in the browser_action popup and in content_scripts. Don't do that. Write a separate content script and use the standard DOM event `selectionchange`, look for examples around, there are plenty. – wOxxOm Jul 26 '20 at 18:52

1 Answers1

1

You'll need to register a content_script that houses the functionality you want to handle.

In your manifest include the script like so:

  content_scripts: [
    {
      js: ['content-script.js'], // <--- have your functionality defined here
      matches: ['<all_urls>'], // <--- this is the array of URLs you want this functionality to be available on
    },
  ],

The above will allow the content-script.js to be available on all URLs

JoeyDoey
  • 11
  • 3