skip to Main Content

I have this function, works perfectly in unix based OS (Linux, MacOS), but somehow, does not works in Windows, it just simply does not add anything to the clipboard.

This is running in a NextJS App.

export const copyRichContent = async rich => {

    const html = new Blob([rich], { type: 'text/html' })
    const data = new ClipboardItem({ 'text/html': html })
    await navigator.clipboard
         .write([data])
         .then(e => console.log('All good', e))
         .catch(err => {
           console.error(err)
         })

}

  • I already tried with clipboard-pollyfill
  • I tried in Windows with Firefox and Chrome
  • If I use the MIME type "text/plain", it works (but I need to use html)
  • The app is running securely (with HTTPS)
  • I confirmed I have the write text and write text delayed permissions
  • No errors in the catch block

I expect to be working in Windows machines, no matter the browser.

2

Answers


  1. Chosen as BEST ANSWER

    I was not pasting the copied data into a RCE (What a moron, right?).


  2. I) First, use https://permission.site/ to check if copy and past are working in your browser (at the bottom of the page you have the clipboard read/write tests). If it does not work… the problem is not in your code (you may open the console devtools to have more details).

    II) Consider the security aspects. Your code must run in a SECURITY CONTEXT (https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/write). One of the main aspect is that your page must be HTTPS. But read the previous link, it is a good to know link.

    III) On Windows, when you put text/html in the clipboard, you must provide a text/plain alternative.

    Look at this example perfectly working on Windows :

    let button = document.createElement('button')
    button.innerText = 'Copy'
    button.addEventListener('click', async () => {
        const rich = '<p>Hello <b>world 1</b> and go to <a href="">Link</a>! at ' + Date.now() + '</p>'
        console.log('isSecureContext=', window.isSecureContext)
        const plain = new Blob([rich], { type: 'text/plain' })
        const html = new Blob([rich], { type: 'text/html' })
        const data = new ClipboardItem({ 'text/plain': plain, 'text/html': html })
        await navigator.clipboard.write([data])
    })
    document.body.append(button)
    

    IV) Be careful with the RichTextEditor you are using for tests. Some are not working properly (Ex: it will not work if you past your HTML in WordPad). Use an online RichTextEditor to check.

    Keep us posted

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search