Transfer content within <pre> tags to the clipboard using a Vue.js application

I am currently developing a Chrome extension using Vue.js where I aim to copy the content within a pre tag section to the clipboard with the click of a button. By assigning an element ID to the pre tag, I can retrieve the content using a copyToClipboard() method. This is what my code looks like:

<template>
        <div>
          <button @click="copyToClipboard()">Copy To Clipboard</button>
        </div>

The method is defined as follows:

methods : {
copyToClipboard() {
      const textToCopy = document.getElementById('textToBecopied')
      textToCopy.select()
      document.execCommand('copy')
    }
}

Although I believe the method is executing correctly, the function .select that I'm using throws an error stating that it's not a function. Does anyone have a better solution to achieve what I am trying to accomplish?

https://i.stack.imgur.com/gaRHU.png

Answer №1

One way I tackled this issue was by extracting the content within the pre-tag and transferring it to a temporary text area. This allowed me to effectively utilize the select method along with the copy to clipboard functionality.

copyToClipboard() {
  const copyText = document.getElementById('textToBecopied').textContent
  const textArea = document.createElement('textarea')
  textArea.textContent = copyText
  document.body.append(textArea)
  textArea.select()
  document.execCommand('copy')
}

Answer №2

The method select() in HTMLInputElement is used to highlight and select all the text found within a <textarea> or an <input> element that contains a text field.

A <pre> element identified by

document.getElementById('textToBecopied')
can be used for this purpose as well.

To retrieve the text, utilize Node.textContent. When it comes to copying to the clipboard, refer to the Clipboard API.

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

Tips for implementing multi-language URL routing in a Node.js application

I am seeking guidance on how to handle routing for multi-language URLs in Node.js, Currently, I have the following routes set up where each language generates specific routes as shown below. However, with more than 5 languages, efficiency is becoming a co ...

What is the best way to connect the elements in two separate arrays?

I have a scenario with two arrays and a variable: var Names = ['jack', 'peter', 'jack', 'john']; var Ids = ['1' , '2' , '3' , '4' ]; Also, I have this search varia ...

Automatically populate a dropdown menu with options based on the user's birth date

I successfully managed to populate the drop-down fields for months, days, and years. Furthermore, I was able to calculate the age of the user; however, I have restricted it to a maximum of 13 years. Check out the code snippet below: $('#reg-yr' ...

"Optimize Your Data with PrimeNG's Table Filtering Feature

I'm currently working on implementing a filter table using PrimeNG, but I'm facing an issue with the JSON structure I receive, which has multiple nested levels. Here's an example: { "id": "123", "category": "nice", "place": { "ran ...

How can you identify duplicate entries using Mongoose?

I am currently working on a create function and encountering some code that closely resembles this: if(req.body.test !== undefined) { if(--req.body.test EXISTS IN test (model)--) { DO STUFF } else { ...

React-select fails to trigger form submission when the Enter key is pressed

Currently, I am utilizing Formik and React-Select in my project, and I'm hoping to enable the form submission by pressing enter while focused on a select input. Interestingly, when I'm focused on any other input field and press Enter, the form s ...

Transforming a jQuery menu into an active selection with Vue JS

I am looking to transition away from using jQuery and instead utilize Vue for the front end of a menu. Specifically, I need to add an active class and a 'menu-open' state to the appropriate nested list items, similar to what is achieved in the pr ...

What is the correct way to adjust the style.top attribute of an element using JavaScript?

In order to correct a JavaScript source code, I need to adjust the style.top property of a div element based on an integer parameter from a function called index. Here is the current implementation: div.style.top = (index * 22 + 2)+"px"; However, for lar ...

Using Accordions in Jquery to dynamically adjust page height during ajax calls

I am currently using AJAX to call in a page and animate its height successfully. However, I have encountered an issue with an accordion-like function that is supposed to toggle the visibility of an element and adjust the height of the containing element ac ...

Unable to display information from a repeated `textarea` in ngRepeat

Check out my code on Plunker: https://plnkr.co/edit/rBGQyOpi9lS0QtnCUq4L I'm trying to log the content of each textarea when typing, using the printStuff() function: $scope.printStuff = function(customize, item) { console.log(customize[item.inde ...

Configuring CORS in an Angular JS controller

Having a controller with a service that retrieves JSON from another server, I encountered the following issue: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the ...

How to Use Jquery to Retrieve the Selected Option Value and Append a Parameter

I am attempting to expand the value by adding "&fullpage=true" <select name="navMenu" onchange="go(this.options[this.selectedIndex].value)"> <option value="-">Choose</option> <option value="page.html&amp;nyo=0" class="ccbnLnk" ...

What is the best way to handle asynchronous requests in frontend development with Nuxt.js?

Recently delving into Vue and Nuxt, I have been grappling with a query surrounding asynchronous requests. My understanding so far is that utilizing asyncData along with axios in Nuxt allows for fetching data that can be showcased on the frontend. However, ...

Sorting through an array of objects based on a key and value that match another object

Is it possible to filter or query an array with the following structure? [ { 'xml:id': 'Name1', sex: { '$t': 'M' }, occupation: { n: 1 ...

error message about missing relative modules in vuejs webpack

I am working on a full-stack application using express and the default vue-webpack-boilerplate. The structure of my project is as follows: ├── client │   ├── build │   │   └── ... │   ├── config │   │   └ ...

When comparing two state arrays in React, it is important to note that they will not be considered equal and return a boolean (True

As I attempt to compare two arrays stored in my state, my goal is to set a boolean variable to "true" if they match. However, my current if statement fails to detect equality between the arrays. I'm performing this comparison within a setInterval() f ...

What could be causing my function to not register with my EventListener?

I'm attempting to perform an action when I click on an element. I have added an eventListener to change the value of a variable upon clicking on that element. However, the eventListener is not working as expected. When I debug the code, it seems like ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

Micro Frontend: Implementing a Pubsub System for Scalable Front-End Architecture

Currently, I am developing a large-scale application using the innovative micro front end architecture. The application is split into 5 Micro Apps: (micro-app-A (developed in Vue), micro-app-B (built with Vue), micro-app-C (using Angular), micro-app-D (cre ...

What is required to create a basic application that can function offline while featuring an HTML/CSS user interface?

Newbie inquiry: I am interested in creating a small application that can run offline on a desktop computer. The amount of data to be saved is minimal, so I have the option to use a file or some type of database. However, my main question is: What languag ...