Home > Blockchain >  Copy and paste localStorage data to clipboard on click
Copy and paste localStorage data to clipboard on click

Time:02-06

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));
}

CodePudding user response:

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 */
  }
}

CodePudding user response:

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.

  • Related