0

Goal: create an alert with the user selected text on the active tab that gets triggered when pressing the Chrome extension's icon (instead of opening a popup like most extensions)

Limitation: I understand manifest V3 prevents access to DOM and by extension the window object. Is there an alternative?

With regular JS and access to DOM this suffices: document.getSelection().toString(); or window.getSelection().toString();

I've looked at many SO questions, none seemed to help me solve this issue.

What I have so far:

manifest.json

{
  "name": "Selected text alert",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_title": "Click to show an alert"
  },
  "host_permissions": ["*://*/*"],
  "permissions": ["activeTab", "scripting"],  
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
     "matches": ["https://*/*"],
     "js": ["content.js"]
    }
  ]
}

background.js

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    files: ['content.js']
  });
});

content.js

chrome.action.onClicked.addListener(() => {
    var userSelection = document.getSelection().toString(); //cause window is not available using V3 manifest
    alert(userSelection);
  });

The problem I'm having: When loading the extension to Chrome, selecting any text on a site and pressing the extension icon, I get presented with this error

Chrome extension error

In summary, I have two issues in the above code:

  • How to retrieve user selected text on an active tab (main goal)
  • chrome.action seems to be undefined (shortcoming of current approach)

Thanks!

jlo
  • 2,157
  • 2
  • 17
  • 23
  • 1
    Remove `chrome.action.onClicked.addListener(() => {` from your content script, you already have it in the background script. Actually remove your content script file and `content_scripts` and `host_permissions` from manifest.json and just use a function, [example](https://stackoverflow.com/a/68543098). – wOxxOm Aug 28 '23 at 18:22

1 Answers1

0

Credit to @wOxxOm for pointing out what needed to be done in the comments.

In the end the working code is:

manifest.json

{
  "name": "Selected text alert",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_title": "Click to show an alert"
  },
  "permissions": ["activeTab", "scripting"],  
  "background": {
    "service_worker": "background.js"
  }
}

background.js

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    function: () => {
      alert(getSelection().toString());
    }
  });
});

Load up the extension, go to any website, select text, click on extension icon and you get the following: Alert popup with selected text

jlo
  • 2,157
  • 2
  • 17
  • 23