Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NSApp.servicesMenu in JXA
#!/usr/bin/osascript -l JavaScript
ObjC.import('Cocoa')
function MainMenu() {
function MenuItem(title, action, key) {
return $.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(title, action, key)
}
function MenuItemSeparator() {
return $.NSMenuItem.separatorItem
}
const appName = ''//$.NSProcessInfo.processInfo.processName.js
const mainMenu = $.NSMenu.new
const itemApp = $.NSMenuItem.new
const itemFile = $.NSMenuItem.new
const itemEdit = $.NSMenuItem.new
mainMenu.addItem(itemApp)
mainMenu.addItem(itemFile)
mainMenu.addItem(itemEdit)
const menuApp = $.NSMenu.alloc.initWithTitle(appName)
const menuFile = $.NSMenu.alloc.initWithTitle('File')
const menuEdit = $.NSMenu.alloc.initWithTitle('Edit')
itemApp.submenu = menuApp
itemFile.submenu = menuFile
itemEdit.submenu = menuEdit
NSApp.servicesMenu = $.NSMenu.new
const itemAppServices = $.NSMenuItem.new
itemAppServices.title = 'Services'
itemAppServices.submenu = NSApp.servicesMenu
const itemAppHideOther = MenuItem('Hide Others', 'hideOtherApplications:', 'h')
itemAppHideOther.keyEquivalentModifierMask = $.NSAlternateKeyMask | $.NSCommandKeyMask
menuApp.addItem( MenuItem(`About ${appName}`, null, '') )
menuApp.addItem( /*--------------------------------------------------*/ MenuItemSeparator())
menuApp.addItem( MenuItem('Preferences...', null, ',') )
menuApp.addItem( /*--------------------------------------------------*/ MenuItemSeparator())
menuApp.addItem( itemAppServices )
menuApp.addItem( /*--------------------------------------------------*/ MenuItemSeparator())
menuApp.addItem( MenuItem(`Hide ${appName}`, 'hide:', 'h') )
menuApp.addItem( itemAppHideOther )
menuApp.addItem( MenuItem('Show All', 'unhideAllApplications:', '') )
menuApp.addItem( /*--------------------------------------------------*/ MenuItemSeparator())
menuApp.addItem( MenuItem(`Quit ${appName}`, 'terminate:', 'q') )
menuFile.addItem( MenuItem('New', 'newDocument:', 'n') )
menuFile.addItem( MenuItem('Open...', 'openDocument:', 'o') )
menuEdit.addItem( MenuItem('Undo', 'undo:', 'z') )
return mainMenu
}
App = Application.currentApplication()
App.includeStandardAdditions = true
NSApp = $.NSApplication.sharedApplication
NSApp.setActivationPolicy($.NSApplicationActivationPolicyRegular)
NSApp.activateIgnoringOtherApps(true)
NSApp.mainMenu = MainMenu()
NSApp.run
@BrokenFreelancer
Copy link

BrokenFreelancer commented Aug 20, 2018

hei, it was super useful to find this!

There is one line though that potentially makes the code work a lot better, at least it now in 2018 on High Sierra.

The code seems to work with a much reduced risk of errors adding after line 63:

App.activate()

Hope it can help if anybody else finds this old gist while snooping around for the sparse JXA examples out there. :-) <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment