javascripthtmleventscontenteditablepaste

How to tell if pasted data was copied from my page?


I'm trying to write a wysiwyg editor. I don't want people to be able to paste in foriegn html, so I figured I could convert it to text. But I still want the html to be pasted if it originated from the same element (or across the site if possible).

So is there a way to detect from a paste event where the content came from?


Solution

  • Detect the copy event (https://developer.mozilla.org/en-US/docs/Web/API/Element/copy_event).

    Use the setData API to include a custom data type e.g. text/whatever. This can include pretty much anything, like where the user copied from, when, etc. You can even upload your own custom data representation in there.

    When pasting, grab the corresponding event and look for your custom data type.

    Edit: My bad, didn't read carefully about having to preventDefault.

    document.addEventListener('copy', (event) => {
    
        event.clipboardData.setData('text/test', 'sum text here');
        const selection = document.getSelection();
    
        // Essentially brute force copying selection.
        const range = selection.getRangeAt(0);
        const div = document.createElement('div');
        div.appendChild(range.cloneContents());
        const copy = div.innerHTML;
    
        event.clipboardData.setData('text/html', copy);
        event.preventDefault();
    });
    
    document.addEventListener('paste', (event) => {
        const clipboard = (event.clipboardData || window.clipboardData);
        let pasteTest = clipboard.getData('text/test');
        let paste = clipboard.getData('text/html');
        console.log (paste, '@@@@@@@@@@@', pasteTest);
    });