JavaScript copy to clipboard not working

前端 未结 5 1122
感动是毒
感动是毒 2021-02-12 22:11

I have a function in my script that gives me an error. The function purpose is to copy text from static panel(not textbox or input) with onClick event.

Uncaught

5条回答
  •  心在旅途
    2021-02-12 22:42

    A more recent solution (year 2020) uses the new Clipboard API writeText method which is supported by most modern browsers (see Can I use for more details).

    //If you want to copyText from Element
    function copyTextFromElement(elementID) {
      let element = document.getElementById(elementID); //select the element
      let elementText = element.textContent; //get the text content from the element
      copyText(elementText); //use the copyText function below
    }
    
    //If you only want to put some Text in the Clipboard just use this function
    // and pass the string to copied as the argument.
    function copyText(text) {
      navigator.clipboard.writeText(text);
    }
    This is some text that needs to be copied

提交回复
热议问题