我正在寻找一个简单的解决方案,通过上下文菜单触发器来更改输入字段值。
让我们说改为codeEditorChildComponent.insert()
就足够了,我稍后会尝试添加一些处理。
的manifest.json:
bar
background.js:
{
"manifest_version": 2,
"background" : { "scripts": ["background.js"] },
"permissions": [ "contextMenus", "http://*/*", "https://*/*" ],
"name": "test plugin",
"version": "0.1"
}
答案 0 :(得分:0)
基本理念是
contextmenu
事件并记录e.target
(这是必需的,因为我们不知道chrome上下文菜单api的实际DOM节点,请参阅Issue 39507 )document.activeElement
,因为输入元素会集中在点击getClickHandler
时向内容脚本发送消息"bar"
示例代码:
的manifest.json
{
"manifest_version": 2,
"background" : { "scripts": ["background.js"] },
"permissions": [ "contextMenus", "http://*/*", "https://*/*" ],
"name": "test plugin",
"version": "0.1",
"content_scripts": [
{
"matches": [
"*://*/*"
],
"js": [
"content.js"
],
"all_frames": true
}
]
}
content.js
chrome.runtime.onMessage.addListener(function (request) {
replaceSelectedText(document.activeElement, request.text);
});
function replaceSelectedText(elem, text) {
var start = elem.selectionStart;
var end = elem.selectionEnd;
elem.value = elem.value.slice(0, start) + text + elem.value.substr(end);
elem.selectionStart = start + text.length;
elem.selectionEnd = elem.selectionStart;
}
background.js
function getClickHandler(info, tab) {
chrome.tabs.sendMessage(tab.id, {text: "bar"});
};
chrome.contextMenus.create({
"title" : "change to 'bar'",
"type" : "normal",
"contexts" : ["editable"],
"onclick" : getClickHandler
});
正如@Xan在评论中提到的,如果您只想更新<input>
字段,那么使用input.value = xxx
就可以了;但是,如果您想操纵任意可编辑元素,请参阅Is there a flexible way to modify the contents of an editable element?以获取更多想法。