当我创建上下文类型为 "editable"
的上下文菜单项时,当在 <input>
上打开上下文菜单时,它会显示标签。
chrome.contextMenus.create({
...
contexts: ["editable"]
...
});
当 <input>
时它起作用。是一个普通的文本框,但是当它具有诸如 date
之类的类型时或time
,菜单不再显示:
<input type="date"> <!-- Nope -->
为什么会这样?有没有办法让它出现(仅在可编辑元素上,包括不同类型的 <input>
)?
最佳答案
根据source code只有非只读、非禁用的文本输入元素是“可编辑”
。
解决方案:动态更改上下文菜单项的上下文
。
使用鼠标/键盘事件处理程序为所有/指定的 URL 声明内容脚本,该事件处理程序检查焦点元素并向后台脚本发送消息到 update上下文菜单项的context
相应地变为“page”
或“editable”
。
manifest.json:
"permissions": ["contextMenus"], "content_scripts": [{ "matches": ["<all_urls>"], "js": ["content.js"], "run_at": "document_start" }], "background": { "scripts": ["background.js"], "persistent": false },
content.js:
window.addEventListener('mousedown', toggleContextMenu); window.addEventListener('keydown', toggleContextMenu); function toggleContextMenu(e) { if (e.button == 2 || // "Apps Menu" key e.keyCode == 93 && !e.altKey && !e.shiftKey && !e.ctrlKey && !e.metaKey) { var tag = e.target.localName; var type = e.target.type; var forceMenu = tag == 'input' && /^(date|time|month|color)$/.test(type) || tag == 'select'; chrome.runtime.sendMessage(forceMenu ? 'page' : 'editable'); } }
背景.js:
chrome.contextMenus.create({ id: 'hello', title: 'Hello', contexts: ['editable'] }, function() { var ignoreErrors = chrome.runtime.lastError; }); chrome.contextMenus.onClicked.addListener(function(info, tab) { if (info.menuItemId == 'hello') { console.log('Hello'); } }); chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) { chrome.contextMenus.update('hello', {contexts: [msg]}); });
关于javascript - 输入类型 "date"不可编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38676487/