在manifest_version=3的chrome插件中chrome扩展中chromecontextMenus创建了一个菜单他的作用域是all跟selection但是我想让他没选中文本的时候是禁用的选中文本了 才启用 我使用了chromecontextMenusonShown 但是提示没有这个事件啊
在manifest_version=3的Chrome扩展中,确实没有chrome.contextMenus.onShown事件。但是你可以使用chrome.contextMenus.onShown的替代方案来实现你的需求。
你可以通过监听chrome.contextMenus.onClicked事件来判断是否选中了文本。当用户点击菜单时,该事件将被触发。在事件处理程序中,你可以使用chrome.tabs.query方法来获取当前活动的标签页,并使用chrome.tabs.sendMessage方法向标签页发送消息。在标签页中,你可以使用window.getSelection().toString()方法来获取当前的选中文本。
以下是一个示例代码,演示了如何在选中文本时启用菜单,而在没有选中文本时禁用菜单:
// background.js
// 创建菜单
chrome.contextMenus.create({
id: "myContextMenu",
title: "我的菜单",
contexts: ["all", "selection"],
enabled: false // 初始状态为禁用
});
// 监听菜单点击事件
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "myContextMenu") {
// 在这里处理菜单点击事件
console.log("菜单被点击了");
}
});
// 监听标签页更新事件
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "complete") {
// 获取当前活动的标签页
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0].id === tabId) {
// 检查是否选中了文本
chrome.tabs.sendMessage(tabId, { type: "checkSelection" });
}
});
}
});
// 监听来自标签页的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "selectionStatus") {
// 根据选中状态更新菜单的启用状态
chrome.contextMenus.update("myContextMenu", { enabled: message.isSelected });
}
});
// content.js
// 监听消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "checkSelection") {
// 检查是否选中了文本
const isSelected = window.getSelection().toString().length > 0;
// 发送选中状态给后台页面
chrome.runtime.sendMessage({ type: "selectionStatus", isSelected });
}
});
在上面的示例中,background.js文件是后台脚本,用于处理菜单点击事件和与标签页通信。content.js文件是内容脚本,用于检查当前标签页是否选中了文本,并将选中状态发送给后台页面。
请确保在manifest.json文件中正确引用这两个脚本:
{
"manifest_version": 3,
"name": "我的扩展",
"version": "1.0",
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"permissions": ["contextMenus", "tabs"],
"action": {
"default_popup": "popup.html"
}
}
这样,当用户选中文本时,菜单将启用,否则将禁用。当用户点击菜单时,菜单点击事件将被触发。
原文地址: https://www.cveoy.top/t/topic/jbSE 著作权归作者所有。请勿转载和采集!