I want to display a different menu option depending on whether a number or text is selected.
I've tried playing with content scripts but I can't get them to work in gmail which is where I need it to work. Here is what I have, it works on sites other than开发者_运维技巧 gmail (is it a https thing?)
Background.html
<script src="driver.js"></script>
content_script.js
document.addEventListener("mousedown", function(event){
if(event.button == 2) {
var selection = window.getSelection().toString();
chrome.extension.sendRequest({cmd: selection});
}
}, true);
driver.js
chrome.extension.onRequest.addListener(function(request) {
alert(request.cmd);
});
manifest.json
{
"name": "Context Menu Search",
"description": "Opens the selected text as keyword in a new window",
"version": "0.1",
"permissions": ["contextMenus"],
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["content_script.js"]
}
],
"background_page": "background.html"
}
Selection type changes context menu using chrome extension
You will have to set a listener for mouse down. There is no other way to get the selected text before the menu is created.
See this SO question:
chrome extension context menus, how to display a menu item only when there is no selection?
Here is part of the code the rest is at the link.
document.addEventListener("mousedown", function(event){
//right click
if(event.button == 2) {
if(window.getSelection().toString()) {
chrome.extension.sendRequest({cmd: "createSelectionMenu"});
} else {
chrome.extension.sendRequest({cmd: "createRegularMenu"});
}
}
}, true);
精彩评论