Electron paste value from clipboard

2019-07-17 15:18发布

I am playing with a small electron app to make a simple copy/paste method.

I have registered a hotkey using globalShortcut:

globalShortcut.register(mod + '+' + key, () => { 
 clipboard.writeText(content);
 // Paste content to any input field/app
});

Is it possible for to now go to notepad and press the registered modifier to paste the content?

Example: App loads, registers a shortcut which sets the clipboard with their desired text.

They then go to a form where they want to paste this content and hit their key which pastes it for them?

This is essentially a way for staff to set up common shortcut / snippets of text with whatever key combinations they want. So if they are filling out report 123, they can just hit their key "Ctrl + Shift + R" which pastes the content they have associated with that hotkey.

How can I do this or simulate a Ctrl V to trigger it?

I have tried both RobotJS (doesn't support global shortcuts) and a Java version (preferred to not use anyway).

2条回答
Bombasti
2楼-- · 2019-07-17 15:57

This is due to the lack of the application’s menu with keybindings to the native clipboard. This can be set by creating your own keybidings, which are called accelerators.

In order to be copy/paste, you need to use content.paste() or content.copy(), this methods execute the editing command paste or copy in web page.

So, you could set an accelerator that would call an editing command, such as copy or paste.

Example:

const { app, globalShortcut } = require('electron')

app.on('ready', () => {
  // Register a 'CommandOrControl+Y' shortcut listener.
  globalShortcut.register('CommandOrControl+C', () => {
    // Do stuff when Y and either Command/Control is pressed.
    contents.copy()
  })

})

contents doc

accelerators docs

查看更多
Explosion°爆炸
3楼-- · 2019-07-17 16:05

It worked for me using the following code:

const { app, globalShortcut } = require('electron')
const robot = require('robotjs')

app.on('ready', () => {
    globalShortcut.register('Control+Shift+R', () => {

        console.log('Control+Shift+R is pressed')

        // simulate CTRL+V / CMD+V
        setTimeout(() => {
            robot.keyTap('v', process.platform==='darwin' ? 'command' : 'control')
        }, 150)
    })
})

app.on('will-quit', () => {
    globalShortcut.unregisterAll()
})

The "trick" here is to delay the simulated key press by a certain interval in order to untangle the actual, physical key press and the simulated one. With shorter intervals, I often saw a "v" appear.

You'll need to decide whether to go for a longer delay (less user friendly because of long "wait", but unlikely to mix up keys) or a shorter delay (prompt response, more likely to get wrong result due to key press mixup).

If we're talking about highly repetitive work or big chunks of text, this will probably still be a timesaver.

查看更多
登录 后发表回答