Search code examples
javascriptgoogle-app-maker

Google App Maker, how to create copy to clipboard function


I'm trying to copy text from a text area to the clipboard with a button that runs the following script. I do get the alert of the text copied, but when I try to paste it somewhere the value was not copied.

function copmycomment() {
/*get the text area*/
  var copyCo = app.pages.NewPage.children.Panel2.children.tao;

  /*select the text area*/

  copyCo.focus();

    /*copy the value*/

    document.execCommand("copy");

 alert("copied the text:" + copyCo.value);
}

Solution

  • In Google App Maker, the TextArea widget is an object composed of two HTML elements; The label and the input. When you execute this line:

    var copyCo = app.pages.NewPage.children.Panel2.children.tao;
    

    You are actually selecting an appmaker object and not an HTML element that contains the text; Therefore, when this line of code is executed:

    copyCo.focus();
    

    You are not focusing the text you would like to copy and as a result the document.execCommand("copy"); does not works.

    In order to achieve what you need, please follow the below steps:

    First, In a test page, insert a TextArea widget and below it a Button widget.
    It should resemble something similar to this:
    enter image description here

    Then, add the following code to the onClick event handler of the button:

    var textField = widget.parent.descendants.TextArea1.getElement().children[1];
    textField.select();
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    

    Please Note:
    In the line var textField = widget.parent.descendants.TextArea1.getElement().children[1]; the part widget.parent.descendants.TextArea1 represents the path to the TextArea widget, so depending on how you do things, it might be different for you.

    That should be all. Preview your app and the text should be copied to the clipboard. I hope this helps!