基本思路是
-
在内容脚本中监听contextmenu事件并记录e.target(这是需要的,因为我们不知道chrome上下文菜单api的实际DOM节点,请参阅Issue 39507)我们可以直接使用document.activeElement,因为输入元素会集中在点击上
- 在后台页面中,当
getClickHandler被触发时向内容脚本发送消息
- 在内容脚本中,将 target.value 替换为
"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 在 cmets 中提到的,如果你只是想更新<input> 字段,那么使用input.value = xxx 是可以的;但是,如果您想操作任意可编辑元素,请参阅Is there a flexible way to modify the contents of an editable element? 了解更多想法。