demand
When we select the text on the web page and right-click it, the “use google translate” option will be displayed in the menu. After clicking this option, the Google Translate window will pop up and the selected text will be translated into English.
directory structure
Main knowledge points:
Creation of contextmenus and windows
Main steps
1.manifest. Background and permissions are declared in JSON
"background":{
"scripts":["js/translate.js"],
"persistent":false
},
"permissions":[
"contextMenus"
]
2. create contextmenus in the background and listen for click events
var menuItem = {
"id" : "translate",
"Title": "using Google translate",
"contexts": ["selection"]
};
chrome.contextMenus.create(menuItem);
3. create a window to display translation results
chrome.contextMenus.onClicked.addListener(function(clickData){
if(clickData.menuItemId == "translate" && clickData.selectionText){
var createData = {
url: "https://translate.google.cn/?sl=zh-CN&tl=en&text="+clickData.selectionText+"&op=translate",
type: "popup",
top: 5,
left: 5,
width: screen.availWidth/2,
height: screen.availHeight/2
}
chrome.windows.create(createData);
}
})
Source code
Link:https://pan.baidu.com/s/1hWQo…
Extraction code: sar6