Using javascript to copy text from a text field to the clipboard

Hi all, is there a way to have a button that when pressed uses javascript to select the content within the text field and copy it to the user’s clipboard? The text will have in variables as well as plain text, so would need to copy that too.
Thanks,
Steve

@steve53990 - Have you seen the thread below? Perhaps it will work for you…?

1 Like

Thanks so much. Thought I’d looked through the entire forum, but totally missed this. It also works fairly well. When I paste the only issue is that it loses all its formatting and pastes as a long line of text. Do you know if it is possible to copy and paste keeping the formatting?

Hi Steve,

We’ve received your email regarding this issue. I’ll reply to you here so that others may refer to this thread if they have the same concern.

In this case, by replacing sourceObject.text() with sourceObject.html(), the text will be copied following the HTML format. Therefore, if you paste it into somewhere that supports HTML, you will see the text formatted.

Regards,

1 Like

Thank you Hang. I have tested this and see how it exports. I think I may have confused the situation. What I’m looking for is that the text object retains it’s formatting and line breaks. When I use object.text() I get plain text and when I use object.htmml() I get html. Is it possible to copy the text with its formatting?
Thank you

Thank you for your response.
Please use the following code in your case, but note that it will work for certain browsers such as Chrome and Edge:

var htmlText = prez.object('Shape_1').html();
var text = prez.object('Shape_1').text();

var clipboardItem = new ClipboardItem({
  'text/plain': new Blob(
    [text],
    {type: 'text/plain'}
  ),
  'text/html': new Blob(
    [htmlText],
    {type: 'text/html'}
  )
});

navigator.clipboard.write([clipboardItem]);

Regards,

Thank you for your reply. Regarding it only working for some browsers, is that it won’t work at all. The reason I ask is that I am using it with Edge, but it only copies and pastes the first line only.
It’s fine if it is limited as I can just use plain text. Would just be useful to know. Thank you

Hi Steve,

It should copy all, not just one line as you mentioned. I suspect there might be something unique in your text causing the issue. Could you please send us your project to support@atomisystems.com so that we can investigate?

Regards,