javascriptelectron

Electron: Pasting a string using the context menu


I'm building some app using Electron and React. I would like to retain standard copy-paste functionality, like in a "normal" program/browser.

I've added this code in my Electron script:

app.on('ready', ()=>{
  BrowserWindow.addDevToolsExtension(
    path.join(os.homedir(), '/AppData/Local/Google/Chrome/User Data/Default/Extensions/fmkadmapgofadopljbjfkapdkoienihi/3.6.0_0')
 )
  createWindow();
  const ctxMenu = new Menu();
  ctxMenu.append(new MenuItem({
    label:'Paste',
    click:()=>{console.log('Paste clicked!')}
  }))

  mainWindow.webContents.on('context-menu',(e,params)=>{
    ctxMenu.popup(mainWindow,params.x,params.y)
  })

})

Now, i have no clue how to create the pasting functionality. I see that electron has a "clipboard" api, but how do i setup the connection between a specific HTML element(into which the user would like to paste), and the electron code?

My app is purely a browser-based one, meaning there is no NodeJS code, besides the standard boilerplate of Electron.

Do i need to intercept the right click in the browser, and then some how communicate it with Electron?

Any help will be greatly appreciated.


Solution

  • If anybody is interested, the solution is actually very easy:

    All you need to do is to add a "role" to the menu item:

     ctxMenu.append(new MenuItem({
        label:'Paste',
        role:'paste',
        click:()=>{console.log('Paste clicked!')}
      }))
    

    That's it, works.