Search code examples
javascriptgoogle-chromedomnavigator

in browser JavaScript, I get error message when writing csv text to clipboard


In Browser JavaScript, I am trying to write some CSV data to the clipboard so that that user can paste to excel. Here is my code:

function onClick(){
      var txt=get_some_valid_csv_text()
      var items=[
          new ClipboardItem({
            'text/csv': new Blob([txt], { type: 'text/csv' })
          })
        ]
      navigator.clipboard.write(items)
}

The problem: It doesn't work, and I get this error message in the console:

Uncaught (in promise) DOMException: Sanitized MIME type text/csv not supported on write.


Solution

  • I just found the answer by trial an error. The secret, it seems, is to use text that is formatted as csv with tabs as separator rather than comma. No need for the ClipboardIteminterface, use can just use navigator.clipboard.writeText

    This is the new code

    function onClick(){
          var txt=get_some_valid_csv_text(sep='\t')
          navigator.clipboard.writeText(txt)
    }