Reputation: 12575
I have a simple question regarding the Context Menu Item for Safari Extensions. I only want the context menu item "Menu Item Label A" to appear when the user right clicks on a particular class on the HTML page. Any ideas what types of events I should be listening to or how I should accomplish this? Thank you.
Upvotes: 1
Views: 1389
Reputation: 2829
What you need is an injected script. See the documentation page that Luke linked to, under the heading "Adding Context Information". Your injected script must have a "contextmenu" event handler like this one:
document.addEventListener("contextmenu", function (evt) {
safari.self.tab.setContextMenuEventUserInfo(evt, evt.target.className);
}, false);
In your global page script, you should have something like this:
safari.application.addEventListener("contextmenu", function (evt) {
// evt.userInfo will have the classname of the right-clicked element
if (evt.userInfo == 'my_special_className') {
evt.contextMenu.appendContextMenuItem('myCommandName', 'My Context Menu Item');
} else {
// don't insert the context menu item
}
}, false);
More about injected scripts: https://developer.apple.com/library/archive/documentation/Tools/Conceptual/SafariExtensionGuide/InjectingScripts/InjectingScripts.html
More about setContextMenuEventUserInfo: https://developer.apple.com/documentation/safariextensions/safaricontentbrowsertabproxy
Upvotes: 4