从 Web 扩展将文本插入可编辑字段
Insert text into editable field from web extension
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.
目前我有上下文菜单项,它会打开 window,但将一些文本插入到可编辑字段中被证明是棘手的。到目前为止我管理的最接近的是:
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()
整个 designMode
事情看起来有点奇怪,而且代码不能非常可靠地工作。有一个更好的方法吗?问题的根源是我没有找到任何方法来找到被点击的可编辑字段。
我会这样做:
let code = 'document.activeElement.value = "apple";';
browser.tabs.executeScript(parent_tab_id, {"code": code});
顺便说一下,后台脚本中的 window.close 是 browser.tabs.remove(currentTabId)。您可以通过查询选项卡API(示例2)来获取当前选项卡ID:https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/query#examples
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.
目前我有上下文菜单项,它会打开 window,但将一些文本插入到可编辑字段中被证明是棘手的。到目前为止我管理的最接近的是:
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()
整个 designMode
事情看起来有点奇怪,而且代码不能非常可靠地工作。有一个更好的方法吗?问题的根源是我没有找到任何方法来找到被点击的可编辑字段。
我会这样做:
let code = 'document.activeElement.value = "apple";';
browser.tabs.executeScript(parent_tab_id, {"code": code});
顺便说一下,后台脚本中的 window.close 是 browser.tabs.remove(currentTabId)。您可以通过查询选项卡API(示例2)来获取当前选项卡ID:https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/query#examples