skip to Main Content

So let’s say i have data in localStorage and there’s 25 different names. How do i copy and paste that localStorage data via clipboard by clicking buttons.

This is the code of button that needs to copy localStorage data:

<a href="" onclick="copyjson()"><div id="Shape1"><div id="Shape1_text"><span style="color:#303C49;font-family:Arial;font-size:16px;"><strong>Скопировать данные</strong></span></div></div></a>

I tried to copy using js code, but somehow it only run if i run that through console:

function copyjson() {
    copy(JSON.stringify(localStorage));
}

2

Answers


  1. The copy function is only used for debugging on console, and isn’t actually a function that you can use in scripts (you will see that if you try to access it via window.copy).

    Take a look at the Clipboard API and specifically to the .write method.

    Login or Signup to reply.
  2. You need something like this:

    async function copyContent() {
      try {
        await navigator.clipboard.writeText(
          JSON.stringify(localStorage)
        );
        console.log('Content copied to clipboard');
        /* Resolved - text copied to clipboard successfully */
      } catch (err) {
        console.error('Failed to copy: ', err);
        /* Rejected - text failed to copy to the clipboard */
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search