0

I am writing a chrome extension that shows a contextMenu when there is a selection, which was pretty straight forward:

var item = chrome.contextMenus.create({
   "title": "myTitle",
   "contexts": ["selection"],
   "id": "myItem"
});

Now, I want to create a submenu item for that one, but based on the selected text. I found I was able to do this by adding the callback when it loads, and display the selected text as a submenu item like this:

var item = chrome.contextMenus.create({
   "title": "myTitle",
   "contexts": ["selection"],
   "id": "myItem"
}, function() {
   // Create item with the selected text
   var subItem = chrome.contextMenus.create({
      "title": "%s",
      "contexts": ["selection"],
      "parentId": "myItem",
      "id": "mySubItem"
   });
});

This is working, however I want to do something based on the last two characters of the selected string, but I can't. By adding something inside the function like this:

var selection = "%s";
if(selection.splice(-2) == "ab") { }
var subItem...

It doesn't work, because selection.splice(-2) returns the selected string. It does that, because it's doing "%s".splice(-2) which is just "%s" so it's never actually operating on the selected text. I have verified this because selection.splice(-1) returns "s", it does not return the last character of what was selected.

How can I work with the selected text here?

AdamMc331
  • 16,492
  • 10
  • 71
  • 133

2 Answers2

0

It's going to be difficult.

'%s' only has a specific special meaning when assigned to that property of a context menu. It's obviously not known at the time of creation of the context menu item (nothing is selected yet), so you can't manipulate it.

Chrome is not flexible in terms of text it shows in context menus, as there is no event like onBeforeShowMenu to manipulate that text or a way to specify a function that would return the label for the entry. That is, unless you try and race Chrome on that by updating the context menu when a selection is made.

This is quite complex to do however. This answer shows a potential way to do it.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206
-1

Have you tried using pure JavaScript api? window.getSelection

var selectionText = window.getSelection().toString();
console.log(selectionText.slice(-2));

BTW, I think you should you slice(-2) or substring(selectionText.length - 2), since splice(-2) will change the original array.

Haibara Ai
  • 10,703
  • 2
  • 31
  • 47