0

I am developing a WebExtension, and one feature is to have a context menu item on editable fields, which when selected opens a confirmation window and then pastes a value into the editable field.

At the moment I have the context menu item, which opens the window, but getting some text inserted into the editable field is proving tricky. The closest I have managed so far is:

let code = 'setTimeout(function() {document.designMode = "on";document.execCommand("insertText", false, "apple");document.designMode = "off";}, 1000);';
browser.tabs.executeScript(parent_tab_id, {"code": code});
window.close()

The whole designMode thing seems it bit weird, and the code does not work very reliably. Is there a better way to do this? The root of the problem, is that I don't see any way to find the editable field that was clicked on.

Xan
  • 74,770
  • 16
  • 179
  • 206
Sam Bull
  • 2,559
  • 1
  • 15
  • 17
  • 1
    See [this question](https://stackoverflow.com/questions/28055887/is-there-a-flexible-way-to-modify-the-contents-of-an-editable-element), does that help? – Xan Oct 16 '17 at 10:16

1 Answers1

0

I would do it like this:

let code = 'document.activeElement.value = "apple";';
browser.tabs.executeScript(parent_tab_id, {"code": code});

By the way, window.close inside a background script is browser.tabs.remove(currentTabId). You can get the current tab id by querying the tabs API (example 2): https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/query#examples

Smile4ever
  • 3,491
  • 2
  • 26
  • 34
  • I wasn't clear, but the code is actually running in the popup window, not the background script, hence the window.close(). – Sam Bull Oct 15 '17 at 21:44
  • 1
    document.activeElement was exactly what I needed. In order to not wipe out all the contents, the resulting code is: `let code = 'document.activeElement.value = document.activeElement.value.substr(0, document.activeElement.selectionStart) + "apple" + document.activeElement.value.substr(document.activeElement.selectionEnd);';` – Sam Bull Oct 15 '17 at 21:46