chrome.contextMenus
를 통해 context menu를 추가하고 리스너를 등록할 수 있습니다. 이미지나 텍스트에 대해 context menu를 생성하고 데이터를 받아올 수 있게 해봅시다.
context menu를 사용하는 것은 권한을 필요로 합니다. manifest.json
에 권한 요청을 추가합니다.
// manifest.json
//...
"permissions": ["contextMenus"]
//...
background에서 chrome.runtime.onInstalled
시에 context menu를 추가하도록 코드를 추가합니다.
// scripts/background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
title: "store to Copy Stack", // 메뉴 타이틀
id: "Store", // 식별자
contexts: ["selection", "image"], // 메뉴가 어떤 타입에 대해 활성화될지 결정
});
});
selection (텍스트 드래그 시 생기는 하이라이트)과 image에 대해 context menu가 활성화 되도록 했습니다.
사용 가능한 contexts는 아래 링크 참조
https://developer.chrome.com/docs/extensions/reference/contextMenus/#type-ContextType
selection과 image에 대해 context menu가 활성화 되는 것을 볼 수 있습니다.
// scripts/background.js
// ...
chrome.contextMenus.onClicked.addListener((info) => {
console.log(info);
});
chrome.contextMenus
에 클릭 이벤트 리스너를 추가합니다. selection을 만들고 context menu를 실행해보면
입력한 menu ID와 selectionText가 출력되는 것을 확인할 수 있습니다.
이번엔 이미지에 대해 context menu를 실행해보면
mediaType과 이미지의 srcUrl을 확인할 수 있습니다.