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
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!