Learn how does the clipboard works in electron and how to use it.

Mastering the use of the Clipboard with Electron Framework

Modern GUIs often provide a clipboard manager which supports multiple cut and paste transactions. In this model the clipboard is treated as a stack or scrap book, with new cuts and copies being placed on top of the list of recent transactions.

If your electron App prevents any keyboard event by default and you want to filter the events according to the user actions by yourself (or simply be fancy and add copy/paste buttons in your UI), you may want to know how to handle manually the clipboard.

Accesing the Clibpoard

To access the clipboard, we are going to use following line :

const {clipboard} = require('electron');

The clipboard variable (in the scope), will allow you to copy, paste and use other methods that the clipboard of the OS have to offer.

Retrieve clipboard content

There are 3 ways to retrieve the content :

As Plain text

You can retrieve the content of the clipboard as plain text using the readText method of the clipboard.

const {clipboard} = require('electron');
var content = clipboard.readText();
alert(content);

As HTML

You can retrieve the content of the clipboard but with the markup content using the readHtml method.

const {clipboard} = require('electron');
var content = clipboard.readHtml();
alert(content);

As RTF

You can retrieve the content of the clipboard as RTF (rich text format) using the readRtf method:

const {clipboard} = require('electron');
var content = clipboard.readRtf();
alert(content);

Set clipboard content

There are 3 methods to set the content of the clipboard in your app.

As Plain Text

You can fill the content of the clipboard with plain text using the writeText method.

const {clipboard} = require('electron');
var content = "Text that will be now on the clipboard as text";
clipboard.writeText(content);

As HTML

You can fill the content of the clipboard with markup using the writeText method.

const {clipboard} = require('electron');
var content = "<b>Try to paste this content into some editor</b> and see how this <em>Works</em>";
clipboard.writeHtml(content);

As RTF

You can fill the content of the clipboard as RTF (rich text format) using the writeRtf method:

const {clipboard} = require('electron');
var content = "{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard This is some {\b bold} text.\par }";
clipboard.writeRtf(content);

Read the official documentation of the clipboard here in the repository.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors