├── .editorconfig ├── .gitattributes ├── .github └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── fixtures ├── fixture-menu.js ├── fixture-toggle.html ├── fixture-toggle.js ├── fixture.html ├── fixture.jpg ├── fixture.js └── flower.mp4 ├── index.d.ts ├── index.js ├── license ├── package.json ├── readme.md ├── screenshot.png └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 20 14 | - 18 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/setup-node@v4 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm install 21 | - run: npm test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /fixtures/fixture-menu.js: -------------------------------------------------------------------------------- 1 | import path from 'node:path'; 2 | import {app, BrowserWindow} from 'electron'; 3 | import contextMenu from '../index.js'; 4 | 5 | contextMenu({ 6 | menu: actions => [ 7 | actions.separator(), 8 | actions.copyLink({ 9 | transform: content => `modified_link_${content}`, 10 | }), 11 | actions.separator(), 12 | { 13 | label: 'Unicorn', 14 | }, 15 | actions.separator(), 16 | actions.saveVideo(), 17 | actions.saveVideoAs(), 18 | actions.copyVideoAddress({ 19 | transform: content => `modified_copy_${content}`, 20 | }), 21 | actions.separator(), 22 | actions.copy({ 23 | transform: content => `modified_copy_${content}`, 24 | }), 25 | { 26 | label: 'Invisible', 27 | visible: false, 28 | }, 29 | actions.paste({ 30 | transform: content => `modified_paste_${content}`, 31 | }), 32 | ], 33 | }); 34 | 35 | // eslint-disable-next-line unicorn/prefer-top-level-await 36 | (async () => { 37 | await app.whenReady(); 38 | 39 | await (new BrowserWindow({ 40 | webPreferences: { 41 | spellcheck: true, 42 | }, 43 | })).loadFile(path.join(import.meta.dirname, 'fixture.html')); 44 | })(); 45 | -------------------------------------------------------------------------------- /fixtures/fixture-toggle.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Fixture 6 | 69 | 70 | 71 |

Fixture

72 |
73 | 74 | 75 |
76 |
77 | 78 |
79 | 80 |
81 |
82 | 83 |
84 |
Editable text
85 |
86 | Link 87 |
88 |
89 | Copy rich text 90 | 91 | 92 | -------------------------------------------------------------------------------- /fixtures/fixture-toggle.js: -------------------------------------------------------------------------------- 1 | import path from 'node:path'; 2 | import {app, BrowserWindow} from 'electron'; 3 | 4 | // eslint-disable-next-line unicorn/prefer-top-level-await 5 | (async () => { 6 | await app.whenReady(); 7 | 8 | await (new BrowserWindow({ 9 | webPreferences: { 10 | nodeIntegration: true, 11 | }, 12 | })).loadFile(path.join(import.meta.dirname, 'fixture-toggle.html')); 13 | })(); 14 | -------------------------------------------------------------------------------- /fixtures/fixture.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Fixture 6 | 15 | 16 | 17 |

Fixture

18 |
19 | 20 |
21 | 22 |
23 | 24 |
25 |
26 | 30 |
Editable text
31 |
32 | Link 33 | 34 |
35 |
36 | Copy rich text 37 | 38 | 39 | -------------------------------------------------------------------------------- /fixtures/fixture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sindresorhus/electron-context-menu/1ad08ae5f31211f4210081c59d4fc536e4f26ba8/fixtures/fixture.jpg -------------------------------------------------------------------------------- /fixtures/fixture.js: -------------------------------------------------------------------------------- 1 | import path from 'node:path'; 2 | import {app, BrowserWindow} from 'electron'; 3 | import contextMenu from '../index.js'; 4 | 5 | contextMenu({ 6 | labels: { 7 | cut: 'Configured Cut', 8 | copy: 'Configured Copy', 9 | paste: 'Configured Paste', 10 | save: 'Configured Save Image', 11 | saveImageAs: 'Configured Save Image As…', 12 | copyLink: 'Configured Copy Link', 13 | saveLinkAs: 'Configured Save Link As…', 14 | inspect: 'Configured Inspect', 15 | }, 16 | prepend: () => [ 17 | { 18 | label: 'Unicorn', 19 | }, 20 | { 21 | type: 'separator', 22 | }, 23 | { 24 | type: 'separator', 25 | }, 26 | { 27 | label: 'Invisible', 28 | visible: false, 29 | }, 30 | { 31 | type: 'separator', 32 | }, 33 | { 34 | type: 'separator', 35 | }, 36 | ], 37 | append() {}, 38 | showSelectAll: true, 39 | showCopyImageAddress: true, 40 | showSaveImageAs: true, 41 | showCopyVideoAddress: true, 42 | showSaveVideoAs: true, 43 | showInspectElement: false, 44 | showSaveLinkAs: true, 45 | }); 46 | 47 | // eslint-disable-next-line unicorn/prefer-top-level-await 48 | (async () => { 49 | await app.whenReady(); 50 | 51 | await (new BrowserWindow({ 52 | webPreferences: { 53 | spellcheck: true, 54 | }, 55 | })).loadFile(path.join(import.meta.dirname, 'fixture.html')); 56 | })(); 57 | -------------------------------------------------------------------------------- /fixtures/flower.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sindresorhus/electron-context-menu/1ad08ae5f31211f4210081c59d4fc536e4f26ba8/fixtures/flower.mp4 -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import { 2 | type BrowserWindow, 3 | type BrowserView, 4 | type ContextMenuParams, 5 | type MenuItemConstructorOptions, 6 | type Event as ElectronEvent, 7 | type WebContents, 8 | type WebContentsView, 9 | } from 'electron'; 10 | 11 | export type Labels = { 12 | /** 13 | @default 'Learn Spelling' 14 | */ 15 | readonly learnSpelling?: string; 16 | 17 | /** 18 | The placeholder `{selection}` will be replaced by the currently selected text. 19 | @default 'Look Up “{selection}”' 20 | */ 21 | readonly lookUpSelection?: string; 22 | 23 | /** 24 | @default 'Search with Google' 25 | */ 26 | readonly searchWithGoogle?: string; 27 | 28 | /** 29 | @default 'Cut' 30 | */ 31 | readonly cut?: string; 32 | 33 | /** 34 | @default 'Copy' 35 | */ 36 | readonly copy?: string; 37 | 38 | /** 39 | @default 'Paste' 40 | */ 41 | readonly paste?: string; 42 | 43 | /** 44 | @default 'Select All' 45 | */ 46 | readonly selectAll?: string; 47 | 48 | /** 49 | @default 'Save Image' 50 | */ 51 | readonly saveImage?: string; 52 | 53 | /** 54 | @default 'Save Image As…' 55 | */ 56 | readonly saveImageAs?: string; 57 | 58 | /** 59 | @default 'Save Video' 60 | */ 61 | readonly saveVideo?: string; 62 | 63 | /** 64 | @default 'Save Video As…' 65 | */ 66 | readonly saveVideoAs?: string; 67 | 68 | /** 69 | @default 'Copy Link' 70 | */ 71 | readonly copyLink?: string; 72 | 73 | /** 74 | @default 'Save Link As…' 75 | */ 76 | readonly saveLinkAs?: string; 77 | 78 | /** 79 | @default 'Copy Image' 80 | */ 81 | readonly copyImage?: string; 82 | 83 | /** 84 | @default 'Copy Image Address' 85 | */ 86 | readonly copyImageAddress?: string; 87 | 88 | /** 89 | @default 'Copy Video Address' 90 | */ 91 | readonly copyVideoAddress?: string; 92 | 93 | /** 94 | @default 'Inspect Element' 95 | */ 96 | readonly inspect?: string; 97 | 98 | /** 99 | @default 'Services' 100 | */ 101 | readonly services?: string; 102 | }; 103 | 104 | export type ActionOptions = { 105 | /** 106 | Apply a transformation to the content of the action. 107 | 108 | If you use this on `cut`, `copy`, or `paste`, they will convert rich text to plain text. 109 | */ 110 | readonly transform?: (content: string) => string; 111 | }; 112 | 113 | export type Actions = { 114 | readonly separator: () => MenuItemConstructorOptions; 115 | readonly learnSpelling: (options: ActionOptions) => MenuItemConstructorOptions; 116 | readonly lookUpSelection: (options: ActionOptions) => MenuItemConstructorOptions; 117 | readonly searchWithGoogle: (options: ActionOptions) => MenuItemConstructorOptions; 118 | readonly cut: (options: ActionOptions) => MenuItemConstructorOptions; 119 | readonly copy: (options: ActionOptions) => MenuItemConstructorOptions; 120 | readonly paste: (options: ActionOptions) => MenuItemConstructorOptions; 121 | readonly selectAll: (options: ActionOptions) => MenuItemConstructorOptions; 122 | readonly saveImage: (options: ActionOptions) => MenuItemConstructorOptions; 123 | readonly saveImageAs: (options: ActionOptions) => MenuItemConstructorOptions; 124 | readonly saveVideo: (options: ActionOptions) => MenuItemConstructorOptions; 125 | readonly saveVideoAs: (options: ActionOptions) => MenuItemConstructorOptions; 126 | readonly copyLink: (options: ActionOptions) => MenuItemConstructorOptions; 127 | readonly copyImage: (options: ActionOptions) => MenuItemConstructorOptions; 128 | readonly copyImageAddress: (options: ActionOptions) => MenuItemConstructorOptions; 129 | readonly copyVideoAddress: (options: ActionOptions) => MenuItemConstructorOptions; 130 | readonly inspect: () => MenuItemConstructorOptions; 131 | readonly services: () => MenuItemConstructorOptions; 132 | }; 133 | 134 | export type Options = { 135 | /** 136 | Window or WebView to add the context menu to. 137 | When not specified, the context menu will be added to all existing and new windows. 138 | */ 139 | readonly window?: BrowserWindow | BrowserView | Electron.WebviewTag | WebContents | WebContentsView; 140 | 141 | /** 142 | Should return an array of [menu items](https://electronjs.org/docs/api/menu-item) to be prepended to the context menu. 143 | 144 | `MenuItem` labels may contain the placeholder `{selection}` which will be replaced by the currently selected text as described in `options.labels`. 145 | */ 146 | readonly prepend?: ( 147 | defaultActions: Actions, 148 | parameters: ContextMenuParams, 149 | browserWindow: BrowserWindow | BrowserView | Electron.WebviewTag | WebContents, 150 | event: ElectronEvent 151 | ) => MenuItemConstructorOptions[]; 152 | 153 | /** 154 | Should return an array of [menu items](https://electronjs.org/docs/api/menu-item) to be appended to the context menu. 155 | 156 | `MenuItem` labels may contain the placeholder `{selection}` which will be replaced by the currently selected text as described in `options.labels`. 157 | */ 158 | readonly append?: ( 159 | defaultActions: Actions, 160 | parameters: ContextMenuParams, 161 | browserWindow: BrowserWindow | BrowserView | Electron.WebviewTag | WebContents, 162 | event: ElectronEvent 163 | ) => MenuItemConstructorOptions[]; 164 | 165 | /** 166 | Show the `Learn Spelling {selection}` menu item when right-clicking text. 167 | 168 | Even if `true`, the `spellcheck` preference in browser window must still be enabled. It will also only show when right-clicking misspelled words. 169 | 170 | @default true 171 | */ 172 | readonly showLearnSpelling?: boolean; 173 | 174 | /** 175 | Show the `Look Up {selection}` menu item when right-clicking text. 176 | 177 | @default true 178 | */ 179 | readonly showLookUpSelection?: boolean; 180 | 181 | /** 182 | Show the `Search with Google` menu item when right-clicking text. 183 | 184 | @default true 185 | */ 186 | readonly showSearchWithGoogle?: boolean; 187 | 188 | /** 189 | Show the `Select All` menu item when right-clicking in a window. 190 | 191 | Default: `false` on macOS, `true` on Windows and Linux 192 | */ 193 | readonly showSelectAll?: boolean; 194 | 195 | /** 196 | Show the `Copy Image` menu item when right-clicking on an image. 197 | 198 | @default true 199 | */ 200 | readonly showCopyImage?: boolean; 201 | 202 | /** 203 | Show the `Copy Image Address` menu item when right-clicking on an image. 204 | 205 | @default false 206 | */ 207 | readonly showCopyImageAddress?: boolean; 208 | 209 | /** 210 | Show the `Save Image` menu item when right-clicking on an image. 211 | 212 | @default false 213 | */ 214 | readonly showSaveImage?: boolean; 215 | 216 | /** 217 | Show the `Save Image As…` menu item when right-clicking on an image. 218 | 219 | @default false 220 | */ 221 | readonly showSaveImageAs?: boolean; 222 | 223 | /** 224 | Show the `Copy Video Address` menu item when right-clicking on a video. 225 | 226 | @default false 227 | */ 228 | readonly showCopyVideoAddress?: boolean; 229 | 230 | /** 231 | Show the `Save Video` menu item when right-clicking on a video. 232 | 233 | @default false 234 | */ 235 | readonly showSaveVideo?: boolean; 236 | 237 | /** 238 | Show the `Save Video As…` menu item when right-clicking on a video. 239 | 240 | @default false 241 | */ 242 | readonly showSaveVideoAs?: boolean; 243 | 244 | /** 245 | Show the `Copy Link` menu item when right-clicking on a link. 246 | 247 | @default true 248 | */ 249 | readonly showCopyLink?: boolean; 250 | 251 | /** 252 | Show the `Save Link As…` menu item when right-clicking on a link. 253 | 254 | @default false 255 | */ 256 | readonly showSaveLinkAs?: boolean; 257 | 258 | /** 259 | Force enable or disable the `Inspect Element` menu item. 260 | 261 | Default: [Only in development](https://github.com/sindresorhus/electron-is-dev) 262 | */ 263 | readonly showInspectElement?: boolean; 264 | 265 | /** 266 | Show the system `Services` submenu on macOS. 267 | 268 | @default false 269 | */ 270 | readonly showServices?: boolean; 271 | 272 | /** 273 | Override labels for the default menu items. Useful for i18n. 274 | 275 | The placeholder `{selection}` may be used in any label, and will be replaced by the currently selected text, trimmed to a maximum of 25 characters length. This is useful when localizing the `Look Up “{selection}”` menu item, but can also be used in custom menu items, for example, to implement a `Search Google for “{selection}”` menu item. If there is no selection, the `{selection}` placeholder will be replaced by an empty string. Normally this placeholder is only useful for menu items which will only be shown when there is text selected. This can be checked using `visible: parameters.selectionText.trim().length > 0` when implementing a custom menu item. 276 | 277 | @default {} 278 | 279 | @example 280 | ``` 281 | { 282 | labels: { 283 | copy: 'Configured Copy', 284 | saveImageAs: 'Configured Save Image As…' 285 | } 286 | } 287 | ``` 288 | */ 289 | readonly labels?: Labels; 290 | 291 | /** 292 | Determines whether or not to show the menu. 293 | Can be useful if you for example have other code presenting a context menu in some contexts. 294 | 295 | @example 296 | ``` 297 | { 298 | // Doesn't show the menu if the element is editable 299 | shouldShowMenu: (event, parameters) => !parameters.isEditable 300 | } 301 | ``` 302 | */ 303 | readonly shouldShowMenu?: ( 304 | event: ElectronEvent, 305 | parameters: ContextMenuParams 306 | ) => boolean; 307 | 308 | /** 309 | This option lets you manually pick what menu items to include. It's meant for advanced needs. The default menu with the other options should be enough for most use-cases, and it ensures correct behavior, for example, correct order of menu items. So prefer the `append` and `prepend` option instead of `menu` whenever possible. 310 | 311 | The function passed to this option is expected to return an array of [`MenuItem` constructor options](https://electronjs.org/docs/api/menu-item/). 312 | 313 | The first argument the function receives is an array of default actions that can be used. These actions are functions that can take an object with a transform property (except for `separator` and `inspect`). The transform function will be passed the content of the action and can modify it if needed. If you use `transform` on `cut`, `copy`, or `paste`, they will convert rich text to plain text. 314 | The second argument is [this `parameters` object](https://electronjs.org/docs/api/web-contents/#event-context-menu). 315 | The third argument is the [BrowserWindow](https://electronjs.org/docs/api/browser-window/) the context menu was requested for. 316 | The fourth argument is an Array of menu items for dictionary suggestions. This should be used if you wish to implement spellcheck in your custom menu. 317 | The last argument is the event object passed to the `context-menu` event in web contents. 318 | 319 | Even though you include an action, it will still only be shown/enabled when appropriate. For example, the `saveImage` action is only shown when right-clicking an image. 320 | 321 | `MenuItem` labels may contain the placeholder `{selection}` which will be replaced by the currently selected text as described in `options.labels`. 322 | 323 | The following options are ignored when `menu` is used: 324 | 325 | - `showLearnSpelling` 326 | - `showLookUpSelection` 327 | - `showSearchWithGoogle` 328 | - `showSelectAll` 329 | - `showCopyImage` 330 | - `showCopyImageAddress` 331 | - `showSaveImageAs` 332 | - `showCopyVideoAddress` 333 | - `showSaveVideo` 334 | - `showSaveVideoAs` 335 | - `showCopyLink` 336 | - `showSaveLinkAs` 337 | - `showInspectElement` 338 | - `showServices` 339 | 340 | To get spellchecking, “Correct Automatically”, and “Learn Spelling” in the menu, please enable the `spellcheck` preference in browser window: `new BrowserWindow({webPreferences: {spellcheck: true}})` 341 | 342 | @default [...dictionarySuggestions, defaultActions.separator(), defaultActions.separator(), defaultActions.learnSpelling(), defaultActions.separator(), defaultActions.lookUpSelection(), defaultActions.separator(),defaultActions.searchWithGoogle(), defaultActions.cut(), defaultActions.copy(), defaultActions.paste(), defaultActions.selectAll(), defaultActions.separator(), defaultActions.saveImage(), defaultActions.saveImageAs(), defaultActions.saveVideo(), defaultActions.saveVideoAs(), defaultActions.copyLink(), defaultActions.copyImage(), defaultActions.copyImageAddress(), defaultActions.separator(), defaultActions.copyLink(), defaultActions.saveLinkAs(), defaultActions.separator(), defaultActions.inspect()] 343 | */ 344 | readonly menu?: ( 345 | defaultActions: Actions, 346 | parameters: ContextMenuParams, 347 | browserWindow: BrowserWindow | BrowserView | Electron.WebviewTag | WebContents, 348 | dictionarySuggestions: MenuItemConstructorOptions[], 349 | event: ElectronEvent 350 | ) => MenuItemConstructorOptions[]; 351 | 352 | /** 353 | Called when the context menu is shown. 354 | */ 355 | readonly onShow?: (event: ElectronEvent) => void; 356 | 357 | /** 358 | Called when the context menu is closed. 359 | */ 360 | readonly onClose?: (event: ElectronEvent) => void; 361 | }; 362 | 363 | /** 364 | This module gives you a nice extensible context menu with items like `Cut`/`Copy`/`Paste` for text, `Save Image` for images, and `Copy Link` for links. It also adds an `Inspect Element` menu item when in development to quickly view items in the inspector like in Chrome. 365 | 366 | You can use this module directly in both the main and renderer process. 367 | 368 | @example 369 | ``` 370 | import {app, BrowserWindow} from 'electron'; 371 | import contextMenu from 'electron-context-menu'; 372 | 373 | contextMenu({ 374 | showSaveImageAs: true 375 | }); 376 | 377 | let mainWindow; 378 | (async () => { 379 | await app.whenReady(); 380 | 381 | mainWindow = new BrowserWindow({ 382 | webPreferences: { 383 | spellcheck: true 384 | } 385 | }); 386 | })(); 387 | ``` 388 | 389 | @example 390 | ``` 391 | import {app, BrowserWindow} from 'electron'; 392 | import contextMenu from 'electron-context-menu'; 393 | 394 | contextMenu({ 395 | prepend: (defaultActions, parameters, browserWindow) => [ 396 | { 397 | label: 'Rainbow', 398 | // Only show it when right-clicking images 399 | visible: parameters.mediaType === 'image' 400 | }, 401 | { 402 | label: 'Search Google for “{selection}”', 403 | // Only show it when right-clicking text 404 | visible: parameters.selectionText.trim().length > 0, 405 | click: () => { 406 | shell.openExternal(`https://google.com/search?q=${encodeURIComponent(parameters.selectionText)}`); 407 | } 408 | } 409 | ] 410 | }); 411 | 412 | let mainWindow; 413 | (async () => { 414 | await app.whenReady(); 415 | 416 | mainWindow = new BrowserWindow({ 417 | webPreferences: { 418 | spellcheck: true 419 | } 420 | }); 421 | })(); 422 | ``` 423 | 424 | The return value of `contextMenu()` is a function that disposes of the created event listeners: 425 | 426 | @example 427 | ``` 428 | const dispose = contextMenu(); 429 | 430 | dispose(); 431 | ``` 432 | */ 433 | export default function contextMenu(options?: Options): () => void; 434 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import process from 'node:process'; 2 | import electron from 'electron'; 3 | import cliTruncate from 'cli-truncate'; 4 | import {download} from 'electron-dl'; 5 | import isDev from 'electron-is-dev'; 6 | 7 | const webContents = win => win.webContents ?? (win.id && win); 8 | 9 | const decorateMenuItem = menuItem => (options = {}) => { 10 | if (options.transform && !options.click) { 11 | menuItem.transform = options.transform; 12 | } 13 | 14 | return menuItem; 15 | }; 16 | 17 | const removeUnusedMenuItems = menuTemplate => { 18 | let notDeletedPreviousElement; 19 | 20 | return menuTemplate 21 | .filter(menuItem => menuItem !== undefined && menuItem !== false && menuItem.visible !== false && menuItem.visible !== '') 22 | .filter((menuItem, index, array) => { 23 | const toDelete = menuItem.type === 'separator' && (!notDeletedPreviousElement || index === array.length - 1 || array[index + 1].type === 'separator'); 24 | notDeletedPreviousElement = toDelete ? notDeletedPreviousElement : menuItem; 25 | return !toDelete; 26 | }); 27 | }; 28 | 29 | const create = (win, options) => { 30 | const handleContextMenu = (event, properties) => { 31 | if (typeof options.shouldShowMenu === 'function' && options.shouldShowMenu(event, properties) === false) { 32 | return; 33 | } 34 | 35 | const {editFlags} = properties; 36 | const hasText = properties.selectionText.length > 0; 37 | const isLink = Boolean(properties.linkURL); 38 | const can = type => editFlags[`can${type}`] && hasText; 39 | 40 | const defaultActions = { 41 | separator: () => ({type: 'separator'}), 42 | learnSpelling: decorateMenuItem({ 43 | id: 'learnSpelling', 44 | label: '&Learn Spelling', 45 | visible: Boolean(properties.isEditable && hasText && properties.misspelledWord), 46 | click() { 47 | const target = webContents(win); 48 | target.session.addWordToSpellCheckerDictionary(properties.misspelledWord); 49 | }, 50 | }), 51 | lookUpSelection: decorateMenuItem({ 52 | id: 'lookUpSelection', 53 | label: 'Look Up “{selection}”', 54 | visible: process.platform === 'darwin' && hasText && !isLink, 55 | click() { 56 | if (process.platform === 'darwin') { 57 | webContents(win).showDefinitionForSelection(); 58 | } 59 | }, 60 | }), 61 | searchWithGoogle: decorateMenuItem({ 62 | id: 'searchWithGoogle', 63 | label: '&Search with Google', 64 | visible: hasText, 65 | click() { 66 | const url = new URL('https://www.google.com/search'); 67 | url.searchParams.set('q', properties.selectionText); 68 | electron.shell.openExternal(url.toString()); 69 | }, 70 | }), 71 | cut: decorateMenuItem({ 72 | id: 'cut', 73 | label: 'Cu&t', 74 | enabled: can('Cut'), 75 | visible: properties.isEditable, 76 | click(menuItem) { 77 | const target = webContents(win); 78 | 79 | if (!menuItem.transform && target) { 80 | target.cut(); 81 | } else { 82 | properties.selectionText = menuItem.transform ? menuItem.transform(properties.selectionText) : properties.selectionText; 83 | electron.clipboard.writeText(properties.selectionText); 84 | } 85 | }, 86 | }), 87 | copy: decorateMenuItem({ 88 | id: 'copy', 89 | label: '&Copy', 90 | enabled: can('Copy'), 91 | visible: properties.isEditable || hasText, 92 | click(menuItem) { 93 | const target = webContents(win); 94 | 95 | if (!menuItem.transform && target) { 96 | target.copy(); 97 | } else { 98 | properties.selectionText = menuItem.transform ? menuItem.transform(properties.selectionText) : properties.selectionText; 99 | electron.clipboard.writeText(properties.selectionText); 100 | } 101 | }, 102 | }), 103 | paste: decorateMenuItem({ 104 | id: 'paste', 105 | label: '&Paste', 106 | enabled: editFlags.canPaste, 107 | visible: properties.isEditable, 108 | click(menuItem) { 109 | const target = webContents(win); 110 | 111 | if (menuItem.transform) { 112 | let clipboardContent = electron.clipboard.readText(properties.selectionText); 113 | clipboardContent = menuItem.transform ? menuItem.transform(clipboardContent) : clipboardContent; 114 | target.insertText(clipboardContent); 115 | } else { 116 | target.paste(); 117 | } 118 | }, 119 | }), 120 | selectAll: decorateMenuItem({ 121 | id: 'selectAll', 122 | label: 'Select &All', 123 | click() { 124 | webContents(win).selectAll(); 125 | }, 126 | }), 127 | saveImage: decorateMenuItem({ 128 | id: 'saveImage', 129 | label: 'Save I&mage', 130 | visible: properties.mediaType === 'image', 131 | click(menuItem) { 132 | properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL; 133 | download(win, properties.srcURL); 134 | }, 135 | }), 136 | saveImageAs: decorateMenuItem({ 137 | id: 'saveImageAs', 138 | label: 'Sa&ve Image As…', 139 | visible: properties.mediaType === 'image', 140 | click(menuItem) { 141 | properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL; 142 | download(win, properties.srcURL, {saveAs: true}); 143 | }, 144 | }), 145 | saveVideo: decorateMenuItem({ 146 | id: 'saveVideo', 147 | label: 'Save Vide&o', 148 | visible: properties.mediaType === 'video', 149 | click(menuItem) { 150 | properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL; 151 | download(win, properties.srcURL); 152 | }, 153 | }), 154 | saveVideoAs: decorateMenuItem({ 155 | id: 'saveVideoAs', 156 | label: 'Save Video& As…', 157 | visible: properties.mediaType === 'video', 158 | click(menuItem) { 159 | properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL; 160 | download(win, properties.srcURL, {saveAs: true}); 161 | }, 162 | }), 163 | copyLink: decorateMenuItem({ 164 | id: 'copyLink', 165 | label: 'Copy Lin&k', 166 | visible: properties.linkURL.length > 0 && properties.mediaType === 'none', 167 | click(menuItem) { 168 | properties.linkURL = menuItem.transform ? menuItem.transform(properties.linkURL) : properties.linkURL; 169 | 170 | electron.clipboard.write({ 171 | bookmark: properties.linkText, 172 | text: properties.linkURL, 173 | }); 174 | }, 175 | }), 176 | saveLinkAs: decorateMenuItem({ 177 | id: 'saveLinkAs', 178 | label: 'Save Link As…', 179 | visible: properties.linkURL.length > 0 && properties.mediaType === 'none', 180 | click(menuItem) { 181 | properties.linkURL = menuItem.transform ? menuItem.transform(properties.linkURL) : properties.linkURL; 182 | download(win, properties.linkURL, {saveAs: true}); 183 | }, 184 | }), 185 | copyImage: decorateMenuItem({ 186 | id: 'copyImage', 187 | label: 'Cop&y Image', 188 | visible: properties.mediaType === 'image', 189 | click() { 190 | webContents(win).copyImageAt(properties.x, properties.y); 191 | }, 192 | }), 193 | copyImageAddress: decorateMenuItem({ 194 | id: 'copyImageAddress', 195 | label: 'C&opy Image Address', 196 | visible: properties.mediaType === 'image', 197 | click(menuItem) { 198 | properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL; 199 | 200 | electron.clipboard.write({ 201 | bookmark: properties.srcURL, 202 | text: properties.srcURL, 203 | }); 204 | }, 205 | }), 206 | copyVideoAddress: decorateMenuItem({ 207 | id: 'copyVideoAddress', 208 | label: 'Copy Video Ad&dress', 209 | visible: properties.mediaType === 'video', 210 | click(menuItem) { 211 | properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL; 212 | 213 | electron.clipboard.write({ 214 | bookmark: properties.srcURL, 215 | text: properties.srcURL, 216 | }); 217 | }, 218 | }), 219 | inspect: () => ({ 220 | id: 'inspect', 221 | label: 'I&nspect Element', 222 | click() { 223 | webContents(win).inspectElement(properties.x, properties.y); 224 | 225 | if (webContents(win).isDevToolsOpened()) { 226 | webContents(win).devToolsWebContents.focus(); 227 | } 228 | }, 229 | }), 230 | services: () => ({ 231 | id: 'services', 232 | label: 'Services', 233 | role: 'services', 234 | visible: process.platform === 'darwin' && (properties.isEditable || hasText), 235 | }), 236 | }; 237 | 238 | const shouldShowInspectElement = typeof options.showInspectElement === 'boolean' ? options.showInspectElement : isDev; 239 | const shouldShowSelectAll = options.showSelectAll || (options.showSelectAll !== false && process.platform !== 'darwin'); 240 | 241 | function word(suggestion) { 242 | return { 243 | id: 'dictionarySuggestions', 244 | label: suggestion, 245 | visible: Boolean(properties.isEditable && hasText && properties.misspelledWord), 246 | click(menuItem) { 247 | const target = webContents(win); 248 | target.replaceMisspelling(menuItem.label); 249 | }, 250 | }; 251 | } 252 | 253 | let dictionarySuggestions = []; 254 | if (hasText && properties.misspelledWord && properties.dictionarySuggestions.length > 0) { 255 | dictionarySuggestions = properties.dictionarySuggestions.map(suggestion => word(suggestion)); 256 | } else { 257 | dictionarySuggestions.push( 258 | { 259 | id: 'dictionarySuggestions', 260 | label: 'No Guesses Found', 261 | visible: Boolean(hasText && properties.misspelledWord), 262 | enabled: false, 263 | }, 264 | ); 265 | } 266 | 267 | let menuTemplate = [ 268 | dictionarySuggestions.length > 0 && defaultActions.separator(), 269 | ...dictionarySuggestions, 270 | defaultActions.separator(), 271 | options.showLearnSpelling !== false && defaultActions.learnSpelling(), 272 | defaultActions.separator(), 273 | options.showLookUpSelection !== false && defaultActions.lookUpSelection(), 274 | defaultActions.separator(), 275 | options.showSearchWithGoogle !== false && defaultActions.searchWithGoogle(), 276 | defaultActions.separator(), 277 | defaultActions.cut(), 278 | defaultActions.copy(), 279 | defaultActions.paste(), 280 | shouldShowSelectAll && defaultActions.selectAll(), 281 | defaultActions.separator(), 282 | options.showSaveImage && defaultActions.saveImage(), 283 | options.showSaveImageAs && defaultActions.saveImageAs(), 284 | options.showCopyImage !== false && defaultActions.copyImage(), 285 | options.showCopyImageAddress && defaultActions.copyImageAddress(), 286 | options.showSaveVideo && defaultActions.saveVideo(), 287 | options.showSaveVideoAs && defaultActions.saveVideoAs(), 288 | options.showCopyVideoAddress && defaultActions.copyVideoAddress(), 289 | defaultActions.separator(), 290 | options.showCopyLink !== false && defaultActions.copyLink(), 291 | options.showSaveLinkAs && defaultActions.saveLinkAs(), 292 | defaultActions.separator(), 293 | shouldShowInspectElement && defaultActions.inspect(), 294 | options.showServices && defaultActions.services(), 295 | defaultActions.separator(), 296 | ]; 297 | 298 | if (options.menu) { 299 | menuTemplate = options.menu(defaultActions, properties, win, dictionarySuggestions, event); 300 | } 301 | 302 | if (options.prepend) { 303 | const result = options.prepend(defaultActions, properties, win, event); 304 | 305 | if (Array.isArray(result)) { 306 | menuTemplate.unshift(...result); 307 | } 308 | } 309 | 310 | if (options.append) { 311 | const result = options.append(defaultActions, properties, win, event); 312 | 313 | if (Array.isArray(result)) { 314 | menuTemplate.push(...result); 315 | } 316 | } 317 | 318 | // Filter out leading/trailing separators 319 | // TODO: https://github.com/electron/electron/issues/5869 320 | menuTemplate = removeUnusedMenuItems(menuTemplate); 321 | 322 | for (const menuItem of menuTemplate) { 323 | // Apply custom labels for default menu items 324 | if (options.labels && options.labels[menuItem.id]) { 325 | menuItem.label = options.labels[menuItem.id]; 326 | } 327 | 328 | // Replace placeholders in menu item labels 329 | if (typeof menuItem.label === 'string' && menuItem.label.includes('{selection}')) { 330 | const selectionString = typeof properties.selectionText === 'string' ? properties.selectionText.trim() : ''; 331 | menuItem.label = menuItem.label.replace('{selection}', cliTruncate(selectionString, 25).replaceAll('&', '&&')); 332 | } 333 | } 334 | 335 | if (menuTemplate.length > 0) { 336 | const menu = electron.Menu.buildFromTemplate(menuTemplate); 337 | 338 | if (typeof options.onShow === 'function') { 339 | menu.on('menu-will-show', options.onShow); 340 | } 341 | 342 | if (typeof options.onClose === 'function') { 343 | menu.on('menu-will-close', options.onClose); 344 | } 345 | 346 | menu.popup(win); 347 | } 348 | }; 349 | 350 | webContents(win).on('context-menu', handleContextMenu); 351 | 352 | return () => { 353 | if (win?.isDestroyed?.()) { 354 | return; 355 | } 356 | 357 | webContents(win).removeListener('context-menu', handleContextMenu); 358 | }; 359 | }; 360 | 361 | export default function contextMenu(options = {}) { 362 | if (process.type === 'renderer') { 363 | throw new Error('Cannot use electron-context-menu in the renderer process!'); 364 | } 365 | 366 | let isDisposed = false; 367 | const disposables = []; 368 | 369 | const init = win => { 370 | if (isDisposed) { 371 | return; 372 | } 373 | 374 | const disposeMenu = create(win, options); 375 | 376 | const disposable = () => { 377 | disposeMenu(); 378 | }; 379 | 380 | webContents(win).once('destroyed', disposable); 381 | }; 382 | 383 | const dispose = () => { 384 | for (const dispose of disposables) { 385 | dispose(); 386 | } 387 | 388 | disposables.length = 0; 389 | isDisposed = true; 390 | }; 391 | 392 | if (options.window) { 393 | const win = options.window; 394 | 395 | // When window is a webview that has not yet finished loading webContents is not available 396 | if (webContents(win) === undefined) { 397 | const onDomReady = () => { 398 | init(win); 399 | }; 400 | 401 | const listenerFunction = win.addEventListener ?? win.addListener; 402 | listenerFunction('dom-ready', onDomReady, {once: true}); 403 | 404 | disposables.push(() => { 405 | win.removeEventListener('dom-ready', onDomReady, {once: true}); 406 | }); 407 | 408 | return dispose; 409 | } 410 | 411 | init(win); 412 | 413 | return dispose; 414 | } 415 | 416 | for (const win of electron.BrowserWindow.getAllWindows()) { 417 | init(win); 418 | } 419 | 420 | const onWindowCreated = (event, win) => { 421 | init(win); 422 | }; 423 | 424 | electron.app.on('browser-window-created', onWindowCreated); 425 | disposables.push(() => { 426 | electron.app.removeListener('browser-window-created', onWindowCreated); 427 | }); 428 | 429 | return dispose; 430 | } 431 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "electron-context-menu", 3 | "version": "4.1.0", 4 | "description": "Context menu for your Electron app", 5 | "license": "MIT", 6 | "repository": "sindresorhus/electron-context-menu", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": { 15 | "types": "./index.d.ts", 16 | "default": "./index.js" 17 | }, 18 | "sideEffects": false, 19 | "engines": { 20 | "node": ">=18" 21 | }, 22 | "scripts": { 23 | "start": "electron fixtures/fixture.js", 24 | "test": "xo && ava && tsc index.d.ts", 25 | "start-fixture2": "electron fixtures/fixture-menu.js", 26 | "start-fixture3": "electron fixtures/fixture-toggle.js" 27 | }, 28 | "files": [ 29 | "index.js", 30 | "index.d.ts" 31 | ], 32 | "keywords": [ 33 | "electron", 34 | "app", 35 | "context", 36 | "right-click", 37 | "menu", 38 | "extensible", 39 | "save", 40 | "image", 41 | "spellchecking", 42 | "spellcheck", 43 | "spelling", 44 | "spell", 45 | "check", 46 | "correct", 47 | "word", 48 | "words", 49 | "dictionary" 50 | ], 51 | "dependencies": { 52 | "cli-truncate": "^4.0.0", 53 | "electron-dl": "^4.0.0", 54 | "electron-is-dev": "^3.0.1" 55 | }, 56 | "devDependencies": { 57 | "@types/node": "^20.12.7", 58 | "ava": "^6.1.2", 59 | "electron": "^30.0.1", 60 | "typescript": "^5.4.5", 61 | "xo": "^0.58.0" 62 | }, 63 | "xo": { 64 | "envs": [ 65 | "node", 66 | "browser" 67 | ] 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # electron-context-menu 2 | 3 | > Context menu for your [Electron](https://electronjs.org) app 4 | 5 | 6 | 7 | Electron doesn't have a built-in context menu. You're supposed to handle that yourself. But it's both tedious and hard to get right. This module gives you a nice extensible context menu with spellchecking and items like `Cut`/`Copy`/`Paste` for text, `Save Image` for images, and `Copy Link` for links. It also adds an `Inspect Element` menu item when in development to quickly view items in the inspector like in Chrome. 8 | 9 | This package can only be used in the main process. 10 | 11 | ## Install 12 | 13 | ```sh 14 | npm install electron-context-menu 15 | ``` 16 | 17 | *Requires Electron 30 or later.* 18 | 19 | ## Usage 20 | 21 | ```js 22 | import {app, BrowserWindow} from 'electron'; 23 | import contextMenu from 'electron-context-menu'; 24 | 25 | contextMenu({ 26 | showSaveImageAs: true 27 | }); 28 | 29 | let mainWindow; 30 | (async () => { 31 | await app.whenReady(); 32 | 33 | mainWindow = new BrowserWindow(); 34 | })(); 35 | ``` 36 | 37 | Advanced example: 38 | 39 | ```js 40 | import {app, BrowserWindow, shell} from 'electron'; 41 | import contextMenu from 'electron-context-menu'; 42 | 43 | contextMenu({ 44 | prepend: (defaultActions, parameters, browserWindow) => [ 45 | { 46 | label: 'Rainbow', 47 | // Only show it when right-clicking images 48 | visible: parameters.mediaType === 'image' 49 | }, 50 | { 51 | label: 'Search Google for “{selection}”', 52 | // Only show it when right-clicking text 53 | visible: parameters.selectionText.trim().length > 0, 54 | click: () => { 55 | shell.openExternal(`https://google.com/search?q=${encodeURIComponent(parameters.selectionText)}`); 56 | } 57 | } 58 | ] 59 | }); 60 | 61 | let mainWindow; 62 | (async () => { 63 | await app.whenReady(); 64 | 65 | mainWindow = new BrowserWindow(); 66 | })(); 67 | ``` 68 | 69 | The return value of `contextMenu()` is a function that disposes of the created event listeners: 70 | 71 | ```js 72 | const dispose = contextMenu(); 73 | 74 | dispose(); 75 | ``` 76 | 77 | ## API 78 | 79 | ### contextMenu(options?) 80 | 81 | Creates a context menu and returns a dispose function. 82 | 83 | ### options 84 | 85 | Type: `object` 86 | 87 | #### window 88 | 89 | Type: `BrowserWindow | BrowserView | WebViewTag | WebContents | WebContentsView` 90 | 91 | Window or WebView to add the context menu to. 92 | 93 | When not specified, the context menu will be added to all existing and new windows. 94 | 95 | #### prepend 96 | 97 | Type: `Function` 98 | 99 | Should return an array of [`MenuItem`](https://electronjs.org/docs/api/menu-item/)'s to be prepended to the context menu. 100 | 101 | The first argument is an array of default actions that can be used. The second argument is [this `parameters` object](https://electronjs.org/docs/api/web-contents/#event-context-menu). The third argument is the [BrowserWindow](https://electronjs.org/docs/api/browser-window/) the context menu was requested for. The fourth argument is the context menu event. 102 | 103 | `MenuItem` labels may contain the placeholder `{selection}` which will be replaced by the currently selected text as described in [`options.labels`](#labels). 104 | 105 | #### append 106 | 107 | Type: `Function` 108 | 109 | Should return an array of [`MenuItem`](https://electronjs.org/docs/api/menu-item/)'s to be appended to the context menu. 110 | 111 | The first argument is an array of default actions that can be used. The second argument is [this `parameters` object](https://electronjs.org/docs/api/web-contents/#event-context-menu). The third argument is the [BrowserWindow](https://electronjs.org/docs/api/browser-window/) the context menu was requested for. The fourth argument is the context menu event. 112 | 113 | `MenuItem` labels may contain the placeholder `{selection}` which will be replaced by the currently selected text as described in [`options.labels`](#labels). 114 | 115 | #### showLearnSpelling 116 | 117 | Type: `boolean`\ 118 | Default: `true` 119 | 120 | Show the `Learn Spelling {selection}` menu item when right-clicking text. 121 | 122 | The spellcheck will only show when right-clicking misspelled words. 123 | 124 | #### showLookUpSelection 125 | 126 | Type: `boolean`\ 127 | Default: `true` 128 | 129 | Show the `Look Up {selection}` menu item when right-clicking text. 130 | 131 | #### showSearchWithGoogle 132 | 133 | Type: `boolean`\ 134 | Default: `true` 135 | 136 | Show the `Search with Google` menu item when right-clicking text. 137 | 138 | #### showSelectAll 139 | 140 | Type: `boolean`\ 141 | Default: `false` on macOS, `true` on Windows and Linux 142 | 143 | Show the `Select All` menu item when right-clicking in a window. 144 | 145 | #### showCopyImage 146 | 147 | Type: `boolean`\ 148 | Default: `true` 149 | 150 | Show the `Copy Image` menu item when right-clicking on an image. 151 | 152 | #### showCopyImageAddress 153 | 154 | Type: `boolean`\ 155 | Default: `false` 156 | 157 | Show the `Copy Image Address` menu item when right-clicking on an image. 158 | 159 | #### showSaveImage 160 | 161 | Type: `boolean`\ 162 | Default: `false` 163 | 164 | Show the `Save Image` menu item when right-clicking on an image. 165 | 166 | #### showSaveImageAs 167 | 168 | Type: `boolean`\ 169 | Default: `false` 170 | 171 | Show the `Save Image As…` menu item when right-clicking on an image. 172 | 173 | #### showCopyVideoAddress 174 | 175 | Type: `boolean`\ 176 | Default: `false` 177 | 178 | Show the `Copy Video Address` menu item when right-clicking on a video. 179 | 180 | #### showSaveVideo 181 | 182 | Type: `boolean`\ 183 | Default: `false` 184 | 185 | Show the `Save Video` menu item when right-clicking on a video. 186 | 187 | #### showSaveVideoAs 188 | 189 | Type: `boolean`\ 190 | Default: `false` 191 | 192 | Show the `Save Video As…` menu item when right-clicking on a video. 193 | 194 | #### showCopyLink 195 | 196 | Type: `boolean`\ 197 | Default: `true` 198 | 199 | Show the `Copy Link` menu item when right-clicking on a link. 200 | 201 | #### showSaveLinkAs 202 | 203 | Type: `boolean`\ 204 | Default: `false` 205 | 206 | Show the `Save Link As…` menu item when right-clicking on a link. 207 | 208 | #### showInspectElement 209 | 210 | Type: `boolean`\ 211 | Default: [Only in development](https://github.com/sindresorhus/electron-is-dev) 212 | 213 | Force enable or disable the `Inspect Element` menu item. 214 | 215 | #### showServices 216 | 217 | Type: `boolean`\ 218 | Default: `false` 219 | 220 | Show the system `Services` submenu when right-clicking text on macOS. 221 | 222 | Note: Due to [a bug in the Electron implementation](https://github.com/electron/electron/issues/18476), this menu is not identical to the "Services" submenu in the context menus of native apps. Instead, it looks the same as the "Services" menu in the main App Menu. For this reason, it is currently disabled by default. 223 | 224 | #### labels 225 | 226 | Type: `object`\ 227 | Default: `{}` 228 | 229 | Override labels for the default menu items. Useful for i18n. 230 | 231 | The placeholder `{selection}` may be used in any label, and will be replaced by the currently selected text, trimmed to a maximum of 25 characters length. This is useful when localizing the `Look Up “{selection}”` menu item, but can also be used in custom menu items, for example, to implement a `Search Google for “{selection}”` menu item. If there is no selection, the `{selection}` placeholder will be replaced by an empty string. Normally this placeholder is only useful for menu items which will only be shown when there is text selected. This can be checked using `visible: parameters.selectionText.trim().length > 0` when implementing a custom menu item, as shown in the usage example above. 232 | 233 | Format: 234 | 235 | ```js 236 | { 237 | labels: { 238 | copy: 'Copiar', 239 | saveImageAs: 'Guardar imagen como…', 240 | lookUpSelection: 'Consultar “{selection}”' 241 | } 242 | } 243 | ``` 244 | 245 | #### shouldShowMenu 246 | 247 | Type: `Function` 248 | 249 | Determines whether or not to show the menu. Can be useful if you for example have other code presenting a context menu in some contexts. 250 | 251 | The second argument is [this `parameters` object](https://electronjs.org/docs/api/web-contents#event-context-menu). 252 | 253 | Example: 254 | 255 | ```js 256 | { 257 | // Doesn't show the menu if the element is editable 258 | shouldShowMenu: (event, parameters) => !parameters.isEditable 259 | } 260 | ``` 261 | 262 | #### menu 263 | 264 | Type: `Function` 265 | 266 | This option lets you manually pick what menu items to include. It's meant for advanced needs. The default menu with the other options should be enough for most use-cases, and it ensures correct behavior, for example, correct order of menu items. So prefer the `append` and `prepend` option instead of `menu` whenever possible. 267 | 268 | The function passed to this option is expected to return [`MenuItem[]`](https://electronjs.org/docs/api/menu-item/). The first argument the function receives is an array of default actions that can be used. These actions are functions that can take an object with a transform property (except for `separator` and `inspect`). The transform function will be passed the content of the action and can modify it if needed. If you use `transform` on `cut`, `copy`, or `paste`, they will convert rich text to plain text. The second argument is [this `parameters` object](https://electronjs.org/docs/api/web-contents/#event-context-menu). The third argument is the [BrowserWindow](https://electronjs.org/docs/api/browser-window/) the context menu was requested for. The fourth argument is an Array of menu items for dictionary suggestions. This should be used if you wish to implement spellcheck in your custom menu. The last argument is the context menu event. 269 | 270 | Even though you include an action, it will still only be shown/enabled when appropriate. For example, the `saveImage` action is only shown when right-clicking an image. 271 | 272 | `MenuItem` labels may contain the placeholder `{selection}` which will be replaced by the currently selected text as described in [`options.labels`](#labels). 273 | 274 | To get spellchecking, “Correct Automatically”, and “Learn Spelling” in the menu, make sure you have not disabled the `spellcheck` option (it's `true` by default) in `BrowserWindow`. 275 | 276 | The following options are ignored when `menu` is used: 277 | 278 | - `showLookUpSelection` 279 | - `showSearchWithGoogle` 280 | - `showSelectAll` 281 | - `showCopyImage` 282 | - `showCopyImageAddress` 283 | - `showSaveImageAs` 284 | - `showCopyVideoAddress` 285 | - `showSaveVideo` 286 | - `showSaveVideoAs` 287 | - `showCopyLink` 288 | - `showSaveLinkAs` 289 | - `showInspectElement` 290 | - `showServices` 291 | 292 | Default actions: 293 | 294 | - `spellCheck` 295 | - `learnSpelling` 296 | - `separator` 297 | - `lookUpSelection` 298 | - `searchWithGoogle` 299 | - `cut` 300 | - `copy` 301 | - `paste` 302 | - `selectAll` 303 | - `saveImage` 304 | - `saveImageAs` 305 | - `saveVideo` 306 | - `saveVideoAs` 307 | - `copyImage` 308 | - `copyImageAddress` 309 | - `copyVideoAddress` 310 | - `copyLink` 311 | - `saveLinkAs` 312 | - `inspect` 313 | - `services` 314 | 315 | Example for actions: 316 | 317 | ```js 318 | { 319 | menu: (actions, props, browserWindow, dictionarySuggestions) => [ 320 | ...dictionarySuggestions, 321 | actions.separator(), 322 | actions.copyLink({ 323 | transform: content => `modified_link_${content}` 324 | }), 325 | actions.separator(), 326 | { 327 | label: 'Unicorn' 328 | }, 329 | actions.separator(), 330 | actions.copy({ 331 | transform: content => `modified_copy_${content}` 332 | }), 333 | { 334 | label: 'Invisible', 335 | visible: false 336 | }, 337 | actions.paste({ 338 | transform: content => `modified_paste_${content}` 339 | }) 340 | ] 341 | } 342 | ``` 343 | 344 | #### onShow 345 | 346 | Type: `Function` 347 | 348 | Called when the context menu is shown. 349 | 350 | The function receives an [`Event` object](https://developer.mozilla.org/en-US/docs/Web/API/Event). 351 | 352 | #### onClose 353 | 354 | Type: `Function` 355 | 356 | Called when the context menu is closed. 357 | 358 | The function receives an [`Event` object](https://developer.mozilla.org/en-US/docs/Web/API/Event). 359 | 360 | ## Related 361 | 362 | - [electron-util](https://github.com/sindresorhus/electron-util) - Useful utilities for developing Electron apps and modules 363 | - [electron-debug](https://github.com/sindresorhus/electron-debug) - Adds useful debug features to your Electron app 364 | - [electron-store](https://github.com/sindresorhus/electron-store) - Save and load data like user settings, app state, cache, etc 365 | - [electron-reloader](https://github.com/sindresorhus/electron-reloader) - Simple auto-reloading for Electron apps during development 366 | - [electron-serve](https://github.com/sindresorhus/electron-serve) - Static file serving for Electron apps 367 | - [electron-unhandled](https://github.com/sindresorhus/electron-unhandled) - Catch unhandled errors and promise rejections in your Electron app 368 | -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sindresorhus/electron-context-menu/1ad08ae5f31211f4210081c59d4fc536e4f26ba8/screenshot.png -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | 3 | test.todo('write proper tests'); 4 | --------------------------------------------------------------------------------