Clipboard API in ElectronJS

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.

Sometimes developers would like more granular control over basic System behavior such as copy and paste operations. Electron provides us access to the System Clipboard using the built-in clipboard module for this very purpose. Using the clipboard module developers can provide copy and paste functionality for different formats such as an Image file, plain text, HTML markup, etc, using the different Instance methods of this module. This tutorial will demonstrate the different operations supported by the Clipboard API in Electron.

We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.

  • Project Structure:
    Project Structure

Clipboard API in Electron: The clipboard module is used for performing copy and paste operations on the system clipboard. The system clipboard is used throughout the System OS environment and hence any copy-paste operation performed in the Electron application is valid throughout the System OS. The clipboard module can be directly used in the Main Process as well as the Renderer Process of the application. Hence we do not need the Electron remote module to import it.

Example: Follow the give Steps to implement Clipboard API in Electron.



  • Step 1: Navigate to an Empty Directory to setup the project, and run the following command,
    npm init

    To generate the package.json file. Install Electron using npm if it is not installed.

    npm install electron --save

    This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key. Copy any Image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file.
    package.json:

    {
      "name": "electron-clip",
      "version": "1.0.0",
      "description": "Clipboard API in Electron",
      "main": "main.js",
      "scripts": {
        "start": "electron ."
      },
      "keywords": [
        "electron"
      ],
      "author": "Radhesh Khanna",
      "license": "ISC",
      "dependencies": {
        "electron": "^8.3.0"
      }
    }
    
  • Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.

    main.js:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    const { app, BrowserWindow } = require('electron')
      
    function createWindow () {
      
      // Create the browser window.
      const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
      })
      
      // Load the index.html of the app.
      win.loadFile('src/index.html')
      
      // Open the DevTools.
      win.webContents.openDevTools()
    }
      
    // This method will be called when Electron 
    // has finished initialization and is ready 
    // to create browser windows. Some APIs can 
    // only be used after this event occurs. This 
    // method is equivalent to 'app.on('ready', function())'
    app.whenReady().then(createWindow)
      
    // Quit when all windows are closed.
    app.on('window-all-closed', () => {
      
      // On macOS it is common for applications and 
      // their menu bar to stay active until the user 
      // quits explicitly with Cmd + Q
      if (process.platform !== 'darwin') {
        app.quit()
      }
    })
      
    app.on('activate', () => {
      
        // On macOS it's common to re-create a window
        // in the app when the dock icon is clicked and
        // there are no other windows open.
      if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
      }
    })
      
    // In this file, you can include the rest of your 
    // app's specific main process code. You can also 
    // put them in separate files and require them here.

    chevron_right

    
    

  • Step 3: Create the index.html file and index.js file within the src directory. We will also copy the Boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.

    index.html:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>Hello World!</title>
                               /security#csp-meta-tag -->
        <meta http-equiv="Content-Security-Policy" 
              content="script-src 'self' 'unsafe-inline';" />
      </head>
      <body>
        <h1>Hello World!</h1>
        We are using node 
        <script>
            document.write(process.versions.node)
        </script>, Chrome 
        <script>
            document.write(process.versions.chrome)
        </script>, and Electron 
        <script>
            document.write(process.versions.electron)
        </script>.
      
        <h3>Clipboard API in Electron</h3>
        <input id="enter" type="text">
        <button id="copy">Copy</button>
        <button id="paste">Paste</button>
      
        <br><br>
        <textarea name="area" id="area" cols="30" rows="10"></textarea>
      
        <br><br>
        <button id="copyHtml">Copy & Paste HTML</button>
      
        <br><br>
        <button id="copyRtf">
            Copy & Paste RTF (Rich Text Format)
        </button>
      
        <br><br>
        <img src="../assets/image.png" alt="">
        <br><br>
        <button id="copyImage">Copy & Paste Image</button>
       
        <!-- Adding Individual Renderer Process JS File -->
        <script src="index.js"></script>
      </body>
    </html>

    chevron_right

    
    

    Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the Command:

    npm start

    GUI Output

  • Step 4: The buttons do not have any functionality associated with them yet. To change this, add the following code in the index.js file,

    A detailed Explanation of all the Instance methods of the clipboard module used in the code is given below. For more detailed Information on the Clipboard API, refer this link.
    Note – In Linux Environment, there is also a selection clipboard. To use and manipulate the selection clipboard we can simply pass the value selection to all Instance methods of the clipboard module that support it. Also according to the Official Electron documentation, all Experimental Instance methods provided by the clipboard module can be removed in future updates of Electron.

    • clipboard.clear(type) This method is used to clear all System clipboard content.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
    • clipboard.availableFormats(type) This method returns a String[] representing all Supported formats for the given clipboard type such as text/html, text/plain, etc.
      Note – This method does not return consistent values as tested in Windows. It sometimes returns an empty array and sometimes it returns a combination of all possible values supported by the clipboard type. According to the official Electron documentation, this is not expected behaviour.

      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
    • clipboard.writeText(text, type) This method writes the text into the clipboard as plain text format. This method does not have a return type. This method has the same functionality as triggered by Ctrl+C on Windows. In our code, this method is associated with the Copy button.
      • text: String This value cannot be empty.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
    • clipboard.readText(type) This method returns the contents of the clipboard as plain text. It returns a String value containing the text. This method has the same functionality as triggered by Ctrl+V on Windows. In our code, this method is associated with the Paste button.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
    • clipboard.writeHTML(markup, type) This method writes the markup String as HTML markup to the clipboard. This method does not have a return type. In our code, this method is a part of the Copy & Paste HTML button.
      • markup: String This value cannot be empty.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
    • clipboard.readHTML() This method returns the contents of the clipboard as HTML markup. It returns a String value containing the markup. In our code, this method is a part of the Copy & Paste HTML button.
      Note: This method does not always return an HTML markup as tested in Windows. Even if we pass a plain text to the clipboard.writeHTML() method, this method will return the value as plain text only. According to the official Electron documentation, this is not expected behaviour.

      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
    • clipboard.writeRTF(text, type) This method writes the text String as RTF (Rich Text Format) to the clipboard. This method does not have a return type. In our code, this method is a part of the Copy & Paste RTF (Rich Text Format) button.
      • text: String This value cannot be empty.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
    • clipboard.readRTF() This methods returns the contents of the clipboard as RTF. It returns a String value containing the RTF. In our code, this method is a part of the Copy & Paste RTF (Rich Text Format) button.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
    • clipboard.writeImage(image, type) This method writes an image to the clipboard. This method does not have a return type. In our code, this method is a part of the Copy & Paste Image button.
      • image: NativeImage (Optional) The image needs to be a nativeImage as used by Electron NativeImage API for it to be written to the clipboard. If this parameter is not passed, null is used instead. We have used the nativeImage.createFromPath(path) method to create a NativeImage object of the image.png file in the assets folder. For more detailed Information on the nativeImage.createFromPath() method, Refer this link.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
    • clipboard.readImage(type) This method returns the contents of the clipboard as a NativeImage image object. In our code, this method is a part of the Copy & Paste Image button.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.

    index.js: Add the following snippet in that file.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    const electron = require('electron')
      
    // Importing the clipboard Module
    const clipboard = electron.clipboard;
      
    // Importing the nativeImage module 
    const nativeImage = electron.nativeImage
      
    var input = document.getElementById('enter');
    var copy = document.getElementById('copy');
    var paste = document.getElementById('paste');
    var area = document.getElementById('area');
      
    clipboard.clear();
    const formats = clipboard.availableFormats();
    console.log(formats);
      
    copy.addEventListener('click', () => {
        if (input.value) {
            clipboard.writeText(input.value);
            console.log('Copied Text Successfully')
        }
    });
      
    paste.addEventListener('click', () => {
        area.innerText = clipboard.readText();
        console.log('Pasted Text Successfully')
    });
      
    var copyHtml = document.getElementById('copyHtml');
    copyHtml.addEventListener('click', () => {
        clipboard.writeHTML('<b>Hello GeeksForGeeks</b>');
      
        console.log(clipboard.readHTML());
    });
      
    var copyRtf = document.getElementById('copyRtf');
    copyRtf.addEventListener('click', () => {
      clipboard.writeRTF('{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}'
        '\\f0\\pard\nThis is some {\\b bold} text.\\par\n}')
      
      console.log(clipboard.readRTF());
    });
      
    var copyImage = document.getElementById('copyImage');
    copyImage.addEventListener('click', () => {
        const image = nativeImage.createFromPath('/assets/image.png')
        clipboard.writeImage(image);
        console.log('Copied Image Successfully');
      
        console.log(clipboard.readImage());
    });

    chevron_right

    
    

    Note: We have covered all the Instance methods of the clipboard module as used in the code. At this point, we should be able to perform copy and paste operations using the clipboard module. There are however some more Instance methods supported by the Clipboard API which are demonstrated in the Next Step.
    Output:

  • Step 5: Some more Instance method supported by the clipboard module,
    • clipboard.has(format, type) This method is an Experimental method. This method is used to check whether a particular format is supported by the clipboard or not. It returns a Boolean.
      • format: String This value cannot be empty. The format to be checked. We can pass any value such as a plain text, HTML markup, RTF or a NativeImage object.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.

      Note – This method does not always return the correct value as tested in Windows. Even if we pass a format which is supported by the clipboard, the value returned is false. According to the official Electron documentation, this is not expected behaviour.

    • clipboard.read(format) This method is an Experimental method. This method is used to read the format type from the clipboard. It returns a String value containing the format type.
      • format: String This value cannot be empty. The format to be checked. We can pass any value such as a plain text, HTML markup, RTF or a NativeImage object.
    • clipboard.writeBookmark(title, url, type) This method is supported in Windows and macOS only. This method writes the title and the url into the clipboard as a bookmark.
      Note: This method does not work as expected in Windows. Also most of the Windows apps do not support pasting bookmarks into them. For more detailed Information, Refer this link.

      • title: String This value cannot be empty. The title of the bookmark.
      • url: String This value cannot be empty. The url of the bookmark.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
    • clipboard.readBookmark() This method is supported in Windows and macOS only. This method returns an object containing the title and the url as keys representing the bookmark as written to the clipboard using the clipboard.writeBookmark() method. The title and the url keys will be returned as empty when the bookmark isn’t available.
    • clipboard.writeFindText(text) This method is supported in macOS only. This method writes the text to the find pasteboard as plain text. The find pasteboard holds information about the current state of the active application’s find panel pasteboard. For more detailed Information, Refer this link. This method uses synchronous IPC when called from the Renderer Process.
    • clipboard.readFindText() This method is supported in macOS only. It returns a text as String from the find pasteboard. This method uses synchronous IPC when called from the Renderer Process. The value is originally cached when the application initially becomes inactive and is reread from the find pasteboard whenever the application is activated again.
    • clipboard.write(data, type) This method is used to collectively write different formats to the clipboard with the help of the data object. The different format values can then be read individually using their respective read methods or read collectively using the clipboard.read() method which simply returns the data object back containing the various non-empty keys. Any format which was initially not written to the clipboard or was empty will be returned as an empty String.
      • type: String (Optional) Value can be selection (Linux) or clipboard. Default value is clipboard.
      • data: Object It can hold the following parameters.
        • text: String (Optional) The String in plain text format.
        • html: String (Optional) The String in HTML markup format
        • rtf: String (Optional) The String in RTF format.
        • image: NativeImage (Optional) The image needs to be a nativeImage object as used by Electron NativeImage API. If this parameter is not passed, null is used instead.

    Note: This concludes the clipboard module of Electron. The clipboard module does not support any Instance Events or Static method.

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.