Home > Mobile >  How to copy to clipboard a selected text with styling ang images by using javascript?
How to copy to clipboard a selected text with styling ang images by using javascript?

Time:07-01

When a user selects a part of the page with styled texts and images, it is possible to copy all that content (with images and styles) and paste it to MS Word or to an e-mail client by clicking "Copy" in the context menu.

How is it possible to achieve the same result with javascript?

So far, I have found solutions to copy plain text only or by using the depreciated document.execCommand("copy") command.

Is there a solution that works for all modern browsers, including Firefox? If such a function cannot be implemented for security reasons or whatever, could someone please explain why exactly? Because users copy content all the time, why it cannot be done with Javascript?

Edit: I'm trying to show a custom popup with a Copy button when user selects some content on the page. That button should be able to copy all the styling of the selected content, not just plain text. Just like the Copy button in the browser context menu or Ctrl C

CodePudding user response:

As far as I understand, you wanna magically transform HTML, CSS and JavaScript to a text format. This is technically not possible.

CodePudding user response:

Yes, it is possible. I suggest looking at Navigator.clipboard API: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboard You can get the selected HTML Elements, do all kinds of transformation on data and then paste the data in to the clipboard. Multiple formats also supported, such as images, HTML and simple text. Note that if you are going to copy HTML and/or images pasting will not work in simple text editors, only in editors like Word that supports advanced pasting formats.

  • Related