Is it possible to copy/paste with Electron?

Sergio picture Sergio · Apr 24, 2017 · Viewed 7k times · Source

I'm using Electron + Nightmare.js to do unit tests.

I need to copy a string to the clibboard > focus a element > paste the content. Then the test is about if my JavaScript is handling behaving properly.

I read in the electron docs about the clipboard api, and copy/paste in webview, but not sure how that integrates with the Nightmare.js API, probably in a .action as suggested in this issue.

A example would be:

import nightmare from 'nightmare'
nightmare.action('copyPaste', function(name, options, parent, win, renderer, done) {
    // some magic here
});

// and then

let res = await page
    .wait('.my-element-to-render')
    .copyPaste(blob)
    .evaluate(() => {
        return document.querySelector('.my-element').value;
    }).end();
expect(res).to.equal('my pasted string');

Any pointers or experience with this?

From the arguments I get from nightmare.action what is the equivalent to <webview> so I can call its copy/paste method?

Answer

Felix picture Felix · Apr 24, 2017

Copy / Paste isn't working in Electron. This is due to the lack of the application’s menu with keybindings to the native clipboard. You can fix that with this code of JS.

You should also checkout this GitHub repository - its a clean HowTo fix this problem.

CODESNIPPET

var app = require("app");
var BrowserWindow = require("browser-window");
var Menu = require("menu");
var mainWindow = null;

app.on("window-all-closed", function(){
    app.quit();
});

app.on("ready", function () {
    mainWindow = new BrowserWindow({
        width: 980,
        height: 650,
        "min-width": 980,
        "min-height": 650
    });
    mainWindow.openDevTools();
    mainWindow.loadUrl("file://" + __dirname + "/index.html");
    mainWindow.on("closed", function () {
        mainWindow =  null;
    });

    // Create the Application's main menu
    var template = [{
        label: "Application",
        submenu: [
            { label: "About Application", selector: "orderFrontStandardAboutPanel:" },
            { type: "separator" },
            { label: "Quit", accelerator: "Command+Q", click: function() { app.quit(); }}
        ]}, {
        label: "Edit",
        submenu: [
            { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
            { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
            { type: "separator" },
            { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
            { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
            { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
            { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
        ]}
    ];

    Menu.setApplicationMenu(Menu.buildFromTemplate(template));
});