yorkxin / copy-as-markdown

A browser extension to copy tabs and links as Markdown
MIT License
546 stars 83 forks source link

Is "copy as rich text" supported? #160

Open borekb opened 1 month ago

borekb commented 1 month ago

I've had this extension installed for years and used it for Markdown happily, however, some apps (in fact, most apps) only accept rich text pasting, not Markdown, and I've recently realized how powerful this extension is with different formats and so on (kudos for keeping the quality high!).

What I'm not sure about is whether "copy as rich text" is supported somehow or not. It would be a nice addition if it's not, IMO.

yorkxin commented 3 weeks ago

Good question. Although Copy as Markdown is intended for plaintext, I am also curious about whether it is possible to write rich text to the clipboard.

Below is the answer I got from Claude AI. It suggests that writing content as HTML. Not verified, and might need some changes in Copy as Markdown so that it is possible to specify MIME Type...

I'll find some time to do some experiments.


To write rich text (including formatting, images, and other elements) to the clipboard in browser JavaScript, you can use the clipboard-write API and the ClipboardItem constructor.

Here's an example:

// Create a ClipboardItem with rich text content
const richTextContent = '<b>This is bold text</b><br><img src="https://example.com/image.png" width="100" height="100">';
const clipboardItem = new ClipboardItem({ 'text/html': new Blob([richTextContent], { type: 'text/html' }) });

// Write the ClipboardItem to the clipboard
navigator.clipboard.write([clipboardItem])
  .then(() => {
    console.log('Rich text copied to clipboard!');
  })
  .catch((error) => {
    console.error('Failed to copy rich text to clipboard:', error);
  });

In this example, we first create a ClipboardItem with the rich text content, including HTML formatting and an image. We then use the navigator.clipboard.write() method to write the ClipboardItem to the clipboard.

The ClipboardItem constructor takes an object as its argument, where the keys represent the MIME types of the data you want to copy, and the values are the actual data. In this case, we're using the 'text/html' MIME type to represent the rich text.

Keep in mind that the clipboard-write API is relatively new and may not be supported by all browsers. You may want to provide a fallback solution for older browsers, such as using the document.execCommand('copy') method to copy plain text to the clipboard.

borekb commented 3 weeks ago

Thanks for the reply, I've tried the Copy Rich Link extension which doesn't support some nice features that this extension does but it does successfully copy the current page to clipboard in the rich text format.

Its GitHub repo: https://github.com/r7kamura/copy-rich-link