Save data from localStorage to clipboard with a click of a button

Imagine you have a total of 25 different names stored in localStorage. How can you easily copy and paste this data from localStorage to clipboard by simply clicking buttons?

Take a look at the button code that is designed to copy the localStorage data:

<a href="" onclick="copyjson()"><div id="Shape1"><div id="Shape1_text"><span style="color:#303C49;font-family:Arial;font-size:16px;"><strong>Copy Data</strong></span></div></div></a>

I attempted to implement a JavaScript function to copy the data, but for some reason it only works when executed through the console:

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

Answer №1

This is an example of how you can achieve the desired result:

const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(
      JSON.stringify(localStorage)
    );
    console.log('Content successfully copied to clipboard');
    /* Success - content has been copied to clipboard */
  } catch (error) {
    console.error('Failed to copy content: ', error);
    /* Error - unable to copy content to clipboard */
  }
}

Answer №2

The copy method serves the purpose of debugging on console only and is not a function that can be directly utilized in scripts (attempting to access it through window.copy will yield no results).

For a more suitable alternative, consider exploring the capabilities of the Clipboard API, particularly focusing on the .write functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to open a PDF file in a new tab using Angular 4?

When attempting to open a PDF file using the window.open() function, I encountered an issue where the window would open and close automatically, causing the file to be downloaded rather than displayed in a new tab. Despite not having any ad blockers inst ...

Inject Angular environment variables into compiled static Angular files within a Spring Boot application

Currently, I am utilizing Angular and Spring Boot for the development of a website project. During deployment, we execute the command ng build --output-path=../spring-boot-project/src/main/resources/static" in Angular to generate a static folder withi ...

Using Angular to implement a decimal pipe on an input field

I am looking for a way to display comma-separated numbers as the user types in an input field by applying the decimal pipe. I have experimented with ngx-mask, but it seems to only function when the user physically enters the numbers. However, when I manu ...

Error when attempting to assign values in Javascript

One issue I am facing is the lack of values assigned for variables like fname, lname, etc. These variables do not exist on the page until the success function is triggered and it posts to template/orderForm.php. For instance, if I try to console.log(fname) ...

"Delving into the intricacies of Angular's factory

If I have a factory like the one below: app.factory("categoryFactory", function (api, $http, $q) { var selected = null; var categoryList = []; return { getList: function () { var d = $q.defer(); if(categoryL ...

How can I properly assign the final value after applying a discount to prevent undefined index errors?

Developed a new coupon code system for the admin to generate coupons. In the process, there is a need to calculate the final amount to be paid after applying the discount. An if statement was utilized as shown below: if(!empty($discountCode)) { $amou ...

Refreshing page with ReactJS internationalization (i18n) capabilities

Currently, I am utilizing react-i18next within my Reactjs application. An issue that I am encountering is that whenever I switch the language, the app reloads and always reverts back to the main route. Is there a method to redirect to the same page or ch ...

AngularJS textbox failing to recognize line breaks as expected

I am struggling with the following HTML code: <div class="form-group"> <div class="input-group col-sm-12"> <label for="" class="control-label">Comments</label> ...

What would be the best method for refreshing CSS following the dynamic addition of data using jQuery for optimal efficiency?

This paragraph was inserted following an ajax request: <tr id="product1" class = "success"> <td>1</td> <td>product one</td> </tr> The success class gives the row a green background, but this style is not applie ...

Is there a way to automatically change the full screen background on refresh?

Is there a way to have the background image of this website change to different pictures every time the page is refreshed? I'm curious about how this can be achieved. I noticed that Offliberty is able to do this. I tried looking at the source code b ...

Deactivate the other RadioButtons within an Asp.net RadioButtonList when one of them is chosen

Is there a way to disable other asp.net radio buttons when one of them is selected? I have three radio buttons, and I want to disable the other two when one is selected. After doing some research, I managed to disable the other two when the third one is se ...

The table is hidden and the buttons are unresponsive when inserted using jQuery

Exploring blueimp's jQuery-File-Upload Demo has been occupying my time recently. After studying it for several days, I feel like I've gained a solid grasp of how it functions. However, as someone with limited experience in web development, there ...

Creating a new component in Qt using an already imported type

When trying to create a component of an imported type, such as MyObject, the workaround is currently to create a separate MyObjectComponent.qml file within the application. This process is important for creating components from types found in installed QML ...

What could be the reason for the malfunctioning of my express delete request?

When I send a delete request using Postman on my localhost, everything functions correctly. However, when trying to make the same request from my React.js client-side, it doesn't go through. Below is the API request: router.delete("/deletetransaction ...

How to Utilize JQuery for Sticky Elements

I am experimenting with a unique twist on the classic Sticky Element concept. Check out for a typical sticky element example. Instead of the traditional sticky behavior, I am looking to have an element initially anchored to the bottom of the user's ...

Utilizing Vue.js to incorporate the isActive property to the class name within a v-for loop, along with implementing dynamic class names

I am currently using a loop to iterate through some data in my store.js file, and everything is functioning as expected. However, I would like to add a condition to check if the Vue instance is active before applying a specific class to the polygon element ...

Transforming the text to a new line

I have been attempting to format lengthy texts from a JSON file, but I haven't been successful. The text keeps displaying as multiple sections within a single response, which can be seen in the image below. I've tested solutions like word-break a ...

Browser refusing to acknowledge jQuery/JavaScript (bootstrap)

Here is where I include the necessary jQuery libraries and my custom jQuery code: <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <script src= ...

Repeat a command in Discord.js indefinitely

Looking for help with this discord.js code I have. Currently, when someone runs the command "!cat", it sends a random image from r/cats. Here is the snippet: var Discord = require('discord.js'); var bot = new Discord.Client() randomPuppy = requir ...

Guide to setting up a default route that precedes all other routes in Express.js routing

I'm struggling to articulate this question correctly, so please be patient with me. Currently, I have a few routes set up: localhost:3000/index localhost:3000/home localhost:3000/login localhost:3000/forgot However, I would like to add a client n ...