Reputation: 167
I have the following code. This is what it does. When you highlight/select some text on a webpage by clicking and dragging, right click to see the context menu, and when the menu item is clicked, the highlighted text shows up in an alert box. I want to modify this code so that the user doesn't have to highlight any text by click and drag. All they have to do is right click on a word and choose the context menu item. The word/text they right clicked on should appear as alert.
let contextMenuItem = {
"id": "helloWorld",
"title": "Hello World",
"contexts": ["selection"]
};
chrome.contextMenus.removeAll(function() {
chrome.contextMenus.create(contextMenuItem);
});
chrome.contextMenus.onClicked.addListener(function(clickData) {
let inputString = clickData.selectionText;
alert(inputString);
})
Upvotes: 2
Views: 1225
Reputation: 40199
First of all, extensions have a "strict" permission model. When you give permission for contextMenus, you are limited to the following contexts:
"all", "page", "frame", "selection", "link", "editable", "image", "video", "audio", "launcher", "browser_action", or "page_action"
If it had a "word" or even a "text" context, it creates a non consistent user experience. Users are not familiar with right click doing actions on text within a web browser.
If you wanted such action, you need to introduce a content-script to add a mouse event to "automatically" select that word using the JavaScript Selection APIs. If you wanted this, you need to expose more "permissions" to your extension to support this experience. Users might not like that.
If this is the experience the extension needs, just create a content-script which automatically selects that word. Something like this will work, which will create a caret range from the mouse position and modify its selection to that word. Note, within the permissions, I just enabled google.com, this is where the content script will inject.
contentscript.js
document.addEventListener('mouseup', (e) => {
if (e.button !== 2) {
return
}
const selection = window.getSelection()
selection.removeAllRanges()
const range = document.caretRangeFromPoint(e.clientX, e.clientY)
range.expand('word')
selection.addRange(range)
});
background.js
const menu = chrome.contextMenus.create({
'id': 'helloWorld',
'title': 'Hello "%s"',
'contexts': ['selection']
})
chrome.contextMenus.onClicked.addListener((clickData) => {
const inputString = clickData.selectionText
console.log(inputString)
});
manifest.json
{
"name": "contextMenus",
"version": "1.0",
"minimum_chrome_version": "35.0",
"manifest_version": 2,
"permissions": [
"contextMenus"
],
"background": {
"scripts": [
"background.js"
]
},
"content_scripts": [
{
"matches": ["https://*.google.com/*"],
"js": ["contentscript.js"]
}
]
}
Upvotes: 1