Copy to Clipboard Integration in SAP UI5

Preface – This post is part of the UI5 Integration Programs series.

Introduction

Copy to Clipboard functionality refers to the ability of a computer or mobile device to copy selected text or data and temporarily store it in a virtual clipboard. The copied content can then be pasted into another location, such as a document or an email.

The copy to clipboard function can be accessed through a variety of ways, such as right-clicking on the selected content and choosing “Copy” from a menu, or using a keyboard shortcut such as Ctrl+C (on Windows) or Command+C (on Mac). Once the content is copied to the clipboard, it can be pasted into another location using a keyboard shortcut such as Ctrl+V (on Windows) or Command+V (on Mac), or by right-clicking and choosing “Paste” from a menu.

Copy to Clipboard is a widely used feature in modern computing, and is particularly useful for tasks such as copying text from a web page or document, and pasting it into an email or other document without having to retype the content.

Why we need to have a Copy to Clipboard Functionality in Website

Copy to Clipboard functionality is useful in websites for a variety of reasons. Here are a few:

  1. Convenience: Copy to Clipboard makes it easy for users to copy and paste text, links, or other content from a website without having to type it out manually.
  2. Accuracy: Copy to Clipboard can help ensure that users copy and paste content accurately, without introducing errors or typos.
  3. Sharing: Copy to Clipboard makes it easy for users to share content from a website with others via email, chat, or social media.
  4. Productivity: Copy to Clipboard can help users be more productive by allowing them to quickly copy and paste information from a website into other applications, such as word processors or spreadsheets.
  5. Accessibility: Copy to Clipboard can be particularly helpful for users who may have difficulty typing, such as those with disabilities or injuries.

Overall, Copy to Clipboard functionality in websites is a useful tool that can help users save time and be more productive, while also reducing the risk of errors and increasing accuracy.

How to Integrate Copy to Clipboard  functionality in UI5

The copy to clipboard is a very simple functionality of HTML and JavaScript, but quite difficult in case of SAP UI5. There are three steps involved in HTML based copy to clipboard operation:
1. Textarea with text value meant for copy
2. Selection of the text using Select function
3. Copy to Clipboard using Copy function

The same three operations will be performed in SAP UI5.

Before you start coding, create a JavaScript file (here customDOM.js) and keep it in a Js folder with given content:

/**
 * @Author: Rudramani Pandey
 * Purpose: JS File for all Custom HTML DOM operations (copy to clipboard)
 * Modified: 17.02.2023
 */
sap.ui.define([], function () {
    "use strict";

    return {

        createTextArea: function (text) {
            var textArea = document.createElement("textarea");
            textArea.value = text;
            return textArea;
        },

        insertTextArea: function (textArea) {
            document.body.appendChild(textArea);
            return true;
        },

        execCommand: function () {
            return document.execCommand('copy');
        },

        removeChild: function (textArea) {
            document.body.removeChild(textArea);
            return true;
        }
    };
});

Explanation:

In the above code createTextArea would create a HTML element textArea. Then insertTextArea would append it to the body of the HTML. execCommand performs the copy function and removeChild removes the HTML element from the body once our task is done.

Then create a view and have simple text area and copy to clipboard button:
View.xml

<mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
    xmlns:html="http://www.w3.org/1999/xhtml">
    <Shell id="shell">
        <App id="app">
            <pages>
                <Page id="page" title="Copy to Clipboard Integration in SAP UI5">
                    <content>
                        <VBox>
                            <TextArea id="idText" value="This is the text that I am going to copy!"/>
                            <Button text="Copy to Clipboard" press="onPressToClipboard"/>
                        </VBox>
                    </content>
                </Page>
            </pages>
        </App>
    </Shell>
</mvc:View>

Now, create a controller, include the JavaScript file in the define section. Now a function to get the text data from XML file.

Controller.js

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "Test/Test/js/customDOM",
    "sap/m/MessageBox",
    "sap/m/MessageToast"
], function (Controller, customDOM, MessageBox, MessageToast) {
    "use strict";

    return Controller.extend("Test.Test.controller.Main", {
        onInit: function () {

        },

        /** 
         * onPressToClipboard is invoked on click of Copy to Clipboard from UI.
         * Calls getText to receive the text value
         * @param oEvent
         * Output: Value of Text Area in HTML DOM
         */
        onPressToClipboard: function (oEvent) {
            var that = this;
            Promise.all([that.getText(oEvent, "CopyPassword")]).then(function (param) {
                param = param[0];
                var textArea = customDOM.createTextArea(param);
                customDOM.insertTextArea(textArea);
                textArea.select();

                try {
                    var successful = customDOM.execCommand();
                    var sMsg = successful ? "successful" : "unsuccessful";
                    MessageToast.show("Password Copy to Clipboard was " + sMsg);
                } catch (err) {
                    // Error Handled Later
                }
                customDOM.removeChild(textArea);
            }).catch(function (param) {
                MessageBox.error(param.message);
            });
        },

        getText: function (oEvent, type) {
            var that = this;
            return new Promise(function (resolved, rejected) {
                var text = that.byId("idText").getValue();
                return resolved(text);
            });
        }
    });
});

Explanation:

In the above code onPressToClipboard gets text from the function getText, and passes it to the function createTextArea to create a HTML TextArea. The function insertTextArea would pass the TextArea would insert into HTML body. textArea.select() would select the text, and then execCommand would finally copy the selected text to the clipboard.

Output

Copy to Clipboard Integration in SAP UI5

Author

  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.