background.js
// 1. Create the main parent menu item
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "parentMenu",
title: "My Extension Options",
contexts: ["all"] // Shows up on text selection, links, pages, etc.
});
// 2. Create sub-menu items linked to the parent ID
chrome.contextMenus.create({
id: "subMenu1",
parentId: "parentMenu",
title: "Select 5th Option",
contexts: ["all"]
});
chrome.contextMenus.create({
id: "subMenu2",
parentId: "parentMenu",
title: "Clear Selection",
contexts: ["all"]
});
});
// 3. Handle clicks on the sub-menu items
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId === "subMenu1") {
// Inject a script into the active page to select the 5th value
const activeTabId = info.tabId || (tab && tab.id);
debugger;
if (!activeTabId) {
console.error("No active tab ID found.");
return;
}
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: selectFifthValue
});
} else if (info.menuItemId === "subMenu2") {
console.log("Sub-menu 2 clicked!");
}
});
// This function runs directly inside the web page's context
function selectFifthValue() {
const selectElement = document.querySelector('select[formcontrolname="sectionName"]');
if (selectElement && selectElement.options.length >= 5) {
selectElement.selectedIndex = 5;
selectElement.dispatchEvent(new Event('change', { bubbles: true }));
}
else {
console.error("Dropdown not found. Check if your formControlName is correct.");
}
}