컨텍스트 메뉴 항목 추가
사용자가 웹 페이지, 이미지 또는 링크를 마우스 오른쪽 버튼으로 클릭할 때 표시되어 확장 프로그램 동작을 실행하는 사용자 지정 컨텍스트 메뉴 항목을 만듭니다.
컨텍스트 메뉴 항목 추가은(는) CoddyKit의 무료 Browser Extensions Development (Chrome & Edge) 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Browser Extensions Development (Chrome & Edge) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Browser Extensions Development (Chrome & Edge) 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What are Context Menus?
Browser extensions can add custom items to the context menu, which appears when you right-click on a web page.
These items let users perform quick actions related to what they clicked on, like saving an image, translating selected text, or triggering a custom search.
Enabling Context Menus
Before your extension can create context menu items, you need to declare the "contextMenus" permission in your manifest.json file.
This permission tells the browser your extension intends to interact with the context menu API.
{ "manifest_version": 3,
"name": "My Menu Extension",
"version": "1.0",
"permissions": [
"contextMenus"
],
"background": {
"service_worker": "background.js"
}
}The `chrome.contextMenus` API
The chrome.contextMenus API is how your background service worker interacts with context menus.
It provides methods to manage menu items:
create(): To add a new menu item.update(): To change an existing item's properties.remove(): To delete a specific item.removeAll(): To clear all items added by your extension.
Creating Your First Item
To create a context menu item, use chrome.contextMenus.create(). You must provide a unique id and a title.
This example adds a simple item named "My First Item" to the general page context menu.
// background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "myFirstItem",
title: "My First Item",
contexts: ["page"]
});
});Item Properties: ID & Title
Each context menu item needs a unique id. This ID helps you identify which item was clicked later.
The title is the text displayed in the menu. The contexts array specifies where the item should appear.
- id: A unique string identifier.
- title: The user-visible text for the menu item.
- contexts: An array of strings defining where the item shows up.
Responding to Clicks
After creating an item, you'll want to run code when a user clicks it. Use chrome.contextMenus.onClicked.addListener() to listen for these clicks.
The listener receives an info object with details about the click, including the menuItemId, which helps you identify which item was activated.
// background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "logClickItem",
title: "Log This Click",
contexts: ["page"]
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "logClickItem") {
console.log("Item 'Log This Click' was clicked!");
// You can perform other actions here
}
});Context Types for Specific Elements
The contexts property is powerful! It allows you to control exactly where your menu item appears.
Common context types include:
"page": Right-click on any part of the page."selection": Right-click on selected text."link": Right-click on a hyperlink."image": Right-click on an image."video","audio": For media elements.
Example: Search Selected Text
Let's create an item that appears only when text is selected. When clicked, it will open a new tab to search that text on Google.
Notice the selectionText property in the info object when using the "selection" context.
// background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "searchSelected",
title: "Search '%s' on Google", // %s is placeholder for selected text
contexts: ["selection"]
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "searchSelected" && info.selectionText) {
const query = encodeURIComponent(info.selectionText);
const url = `https://www.google.com/search?q=${query}`;
chrome.tabs.create({ url: url });
}
});Updating and Removing Items
You can dynamically change or remove context menu items after they've been created. This is useful for adapting to user preferences or page content.
chrome.contextMenus.update(id, properties): Changes properties like title or contexts.chrome.contextMenus.remove(id): Deletes a specific item.chrome.contextMenus.removeAll(): Deletes all items added by your extension.
Context Menu Challenge
Consider the following manifest.json and background script for an extension.
Which statements about the context menu items created are true?
// manifest.json
{
"manifest_version": 3,
"name": "Test Menu",
"version": "1.0",
"permissions": ["contextMenus"],
"background": {"service_worker": "background.js"}
}
// background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "itemA",
title: "Action A",
contexts: ["page"]
});
chrome.contextMenus.create({
id: "itemB",
title: "Action B",
contexts: ["selection"]
});
chrome.contextMenus.create({
id: "itemC",
title: "Action C",
contexts: ["link"]
});
});Recap: Context Menus
You've learned how to add custom context menu items to your browser extension!
- Declare
"contextMenus"permission inmanifest.json. - Use
chrome.contextMenus.create()in your background script. - Specify
id,title, andcontextsfor each item. - Listen for clicks using
chrome.contextMenus.onClicked.addListener(). - Contexts like
"page","selection","link"allow precise targeting.
These skills enable you to add powerful, context-aware actions to your extension. Next, we'll explore integrating with the Omnibox!
자주 묻는 질문
“컨텍스트 메뉴 항목 추가” 강의는 무료인가요?
네 — “컨텍스트 메뉴 항목 추가” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Browser Extensions Development (Chrome & Edge) 강의 전체를 잠금 해제할 수 있습니다. Browser Extensions Development (Chrome & Edge) 강의에는 총 4개의 강의가 포함되어 있습니다.
“컨텍스트 메뉴 항목 추가”에서 뭘 배우나요?
사용자가 웹 페이지, 이미지 또는 링크를 마우스 오른쪽 버튼으로 클릭할 때 표시되어 확장 프로그램 동작을 실행하는 사용자 지정 컨텍스트 메뉴 항목을 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Browser Extensions Development (Chrome & Edge)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Browser Extensions Development (Chrome & Edge)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Browser Extensions Development (Chrome & Edge)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“컨텍스트 메뉴 항목 추가” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Browser Extensions Development (Chrome & Edge) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Browser Extensions Development (Chrome & Edge) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 컨텍스트 메뉴 항목 추가
- 주소창 키워드 통합
- 주소창 입력에 응답하기
- Commands API를 활용한 키보드 단축키