0

I am building an chrome extension and I have an issue which seems to not have a describefull up-do-date solution:

I'd like to display user selected onpage text in a textbox in my extension's pop-up.

I am aware I have to use sendMessage and onMessage with background script, but can't build it all together in order to work.

Here is my manifest.json:

{
"manifest_version": 3,
"name": "Custom extension",
"description": "my extension",
"version": "1.1",
"permissions": [
    "activeTab",
    "scripting",
    "tabs"
],
"background": {
    "service_worker": "background.js",
    "type": "module"
},
"icons": {
    "16": "/icons/icon16.png",
    "48": "/icons/icon48.png",
    "128": "/icons/icon128.png"
},
"action": {
    "default_icon": {
        "16": "/icons/icon16.png",
        "48": "/icons/icon48.png",
        "128": "/icons/icon128.png"
    },
    "default_title": "Custom extension",
    "default_popup": "console.html"
},
"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js": ["getSelectionText.js", "popup.js"]
    }
]
}

Here is my console.html:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <script src="getSelectionText.js"></script>
  <script src="popup.js"></script>
  <script src="background.js"></script>
</head>

<body>
  <textarea id="selected-text" cols="30" rows="10"></textarea>
</body>

</html>

Here is my getSelectionText.js

document.addEventListener("mouseup", function () {
    var selectedText = window.getSelection().toString();
    if (selectedText) {
        chrome.runtime.sendMessage({ text: selectedText });
    }
});

Here is my background.js:

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.text) {
        chrome.runtime.sendMessage({ text: message.text }, function (response) {
            console.log(response);
        });
    }
});

And lastly - my popup.js:

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.text) {
        document.getElementById("selected-text").value = message.text;
    }
});

Current outcome: Currently, with this code, my textarea stays blank and when I open extension's popup window's console is see this error:

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

Tried multiple solutions and searched the web for a specific solution, but seems that most of the topics in the web are for manifest_version 2 or even 1.

  • 1) remove background.js, getSelectionText.js from disk, from manifest.json, and from html, 2) remove tabs, content_scripts, and background from manifest.json, 3) use chrome.scripting.executeScript in popup.js + getSelection as shown [here](https://stackoverflow.com/a/68543098). If the text should appear immediately replace the click listener with an IIFE e.g. `(async () => { /*code*/ })()` – wOxxOm Mar 20 '23 at 17:33

0 Answers0