Search code examples
javascriptstyleseditorclipboard

Preserving style during copy past in JS. (how get stile from clipboard)


Yesterday I wrote an article about "Sliding Window" Algorithm in MicrosoftVSC editor in *.md format, later I copy/pasted this article from md preview (It is a decorated text, not a Markdown code) to a medium editor. And I been surprised that style and headings are saved.

The question is: What parts of JS recognize the design of text from clipboard?

P.S. When I insert this copied text with styles inside Notepad or Untitled file of MVC it is just a plane text. How did the Medium editor recognized the style, what is the data format in clipboard?

When I again copy this plain text from a notepad, and insert it inside the Medium editor the styles are not appears (as they should). But it's curious how do this styles passed and where do they saved.


Solution

  • Answer on this question lies in DataTranswer object that holds information about paste event. This object holds different versions of saved text. One version is plain/text second version is text/html. The text/html versions contains a decoration.

    console.log("Checking paste operation.")
    document.addEventListener('paste', function(e) {
            console.log("The Past is Happens");
            console.log(e.clipboardData.types);
            ['text/plain','text/html'].forEach( format =>{
              console.log(`Format: ${format}`);
              console.log(e.clipboardData.getData(format));
            });
        });