Copy to clipboard with javascript

How to copy text to the clipboard with Javascript

Copying data from the browser into your clipboard is a small feature, yet a quite powerful one. No more manual selecting & crtl + c does save a bit of time when following larger coding articles. I’ve just added the small clipboard sign next to all my snippets for a reader’s convenience myself. Read on to find out how I did it.

Boilerplate

Create an index.html file, as well as a main.js file in a directory of your choice. Fill the index — file up with the following and let’s jump in.

  lang="en">  charset="UTF-8" />  http-equiv="X-UA-Compatible" content="IE=edge" />  name="viewport" content="width=device-width, initial-scale=1.0" /> Copy to clipboard   With textarea  placeholder="Write your content here and press 'Copy Text'" id="clipboard-area" cols="30" rows="2" >  placeholder="Paste your content here" cols="30" rows="2" >   style="width: 260px" onclick="handleCopyTextFromArea()"> Copy text Without textarea  style="display: flex">  style="width: 260px; margin: 0"> Lorem ipsum, dolor sit amet consectetur adipisicing elit.  placeholder="Paste your content here" cols="30" rows="2" >   style="width: 260px" onclick="handleCopyTextFromParagraph()"> Copy text  src="main.js">   

We’ll have two functions attached to the buttons — handleCopyTextFromArea and

an image that shows a simple html user interface with three textareas and a paragraph

handleCopyTextFromParagraph — let’s fill them with life.

Method 1: execCommand(‘copy’)

While the functionality of this method is deprecated according to MDN docs, it still works well with a textarea — html tag. And even if you do not have such available, creating it — and filling its value with the desired text content — is done very quickly. If you have a text area available, add the following to your index.html

function handleCopyTextFromArea()  const area = document.querySelector('#clipboard-area') area.select(); document.execCommand('copy') > 
  1. Create the textarea element and add it to the DOM.
  2. Populate its value with the text from the paragraph — or any other element.
  3. Use the above execCommand(‘copy’) — method to copy the textual content
  4. Remove the element again.
function handleCopyTextFromParagraph()  const body = document.querySelector('body'); const paragraph = document.querySelector('p'); const area = document.createElement('textarea'); body.appendChild(area); area.value = paragraph.innerText; area.select(); document.execCommand('copy'); body.removeChild(area); > 

If you now try and crtl + v into the textarea to the right, you should see the input being pasted. While this approach does still work very well, modern browsers have implemented their own interfaces to take care of clipboard features. Let’s take a look at that next.

Method 2: Clipboard API

The clipboard API is a modern, promise based approach that solely focuses on the clipboard instead of doing many things at once. It requests you for permission and works only over https, making it more secure by design. According to Can I use, older browsers do not support this functionality, therefor you might want to consider having the alternative in place as well.

Let’s replace the above handleCopyTextFromParagraph function with the following:

function handleCopyTextFromParagraph()  const cb = navigator.clipboard; const paragraph = document.querySelector('p'); cb.writeText(paragraph.innerText).then(() => alert('Text copied')); > 

And that’s about it, really. You might want to replace the .then() — callback with some neater type of user feedback and check for user permission, still — goal achieved — the text is available and ready to be parsed.

UPDATE: Copy to clipboard with Vue 3 directive

If you’re using Vue.js to build your application, you can wrap the above function using a Vue custom directive. Then, you achieve the same functionality by clicking on (or interacting in any other way with) the component that has v-clip bound to it.

Declare the following function inside of you main.js file and have it registered globally after creating the Vue app:

const vClip =  // For Vue 2, you can use bind instead of mounted mounted: (el) =>  el.addEventListener('click', () =>  const cb = navigator.clipboard; // Check if the clicked on element is an input element const input = el.tagName === 'input' ? el : el.querySelector('input'); // Copy the text to clipboard cb.writeText(input.value).then(() => alert('Text copied')); >); >, >; // Create the app and mount it const app = createApp(App); app.directive('clip', vClip); app.mount('#app'); 

Then, assuming you have the following component:

 label="Short link:" v-model="form.result" disabled /> 

You can add the v-clip directive to it:

 label="Short link:" v-clip v-model="form.result" disabled /> 

Источник

Работа с буфером обмена в JavaScript с использованием асинхронного API Clipboard

Существует новое API JavaScript, предназначенное для организации асинхронного доступа к буферу обмена с использованием спецификации, которая всё ещё находится на этапе разработки. До сих пор в веб-разработке стандартным способом копирования текста в буфер обмена является подход, предусматривающий использование метода document.execCommand. Основной недостаток этого подхода заключается в том, что это — синхронная блокирующая операция. Асинхронное API для работы с буфером обмена основано на промисах, одной из его задач является устранение этого недостатка. Оно призвано дать веб-разработчикам более простое в использовании унифицированное API для работы с буфером обмена. Кроме того, это API спроектировано с учётом возможности поддержки множества типов данных, а не только text/plain.

Надо отметить, что сейчас новое API доступно только в Chrome 66+ и поддерживает лишь копирование и вставку обычного текста. Кроме того, работает оно только тогда, когда страница загружена по HTTPS или с localhost, и только в тех случаях, когда страница открыта в текущей активной вкладке браузера.

Запись данных в буфер обмена

Запись данных в буфер обмена — простая операция, реализуемая посредством вызова метода writeText объекта clipboard с передачей ему соответствующего текста.

navigator.clipboard.writeText('Hello Alligator!') .then(() => < // Получилось! >) .catch(err => < console.log('Something went wrong', err); >);

Чтение данных из буфера обмена

Для того чтобы прочитать данные из буфера обмена, используется метод readText . В целях повышения безопасности, помимо того, что страница, читающая данные из буфера обмена, должна быть открыта в активной вкладке браузера, пользователь должен предоставить ей дополнительное разрешение. Браузер автоматически запросит это разрешение при первом вызове readText .

navigator.clipboard.readText() .then(text => < // `text` содержит текст, прочитанный из буфера обмена >) .catch(err => < // возможно, пользователь не дал разрешение на чтение данных из буфера обмена console.log('Something went wrong', err); >);

Практический пример

Разберём простой пример взаимодействия с буфером обмена из JavaScript. Он будет работать лишь в поддерживаемых браузерах. Если хотите, можете своими силами доработать его, добавив механизмы, позволяющие ему функционировать в браузерах, которые пока не поддерживают API Clipboard. Посмотреть, как всё это работает, можно на странице оригинала статьи, в разделе Simple Demo.

 

А вот — JS-код, который отвечает за работу с буфером обмена.

const readBtn = document.querySelector('.read-btn'); const writeBtn = document.querySelector('.write-btn'); const resultsEl = document.querySelector('.clipboard-results'); const inputEl = document.querySelector('.to-copy'); readBtn.addEventListener('click', () => < navigator.clipboard.readText() .then(text =>< resultsEl.innerText = text; >) .catch(err => < console.log('Something went wrong', err); >) >); writeBtn.addEventListener('click', () => < const inputValue = inputEl.value.trim(); if (inputValue) < navigator.clipboard.writeText(inputValue) .then(() => < inputEl.value = ''; if (writeBtn.innerText !== 'Copied!') < const originalText = writeBtn.innerText; writeBtn.innerText = 'Copied!'; setTimeout(() =>< writeBtn.innerText = originalText; >, 1500); > >) .catch(err => < console.log('Something went wrong', err); >) > >);

Как видите, всё тут устроено очень просто. Единственное место, над которым пришлось немного поработать — это код для работы с кнопкой копирования, где мы сначала проверяем, что нам есть что копировать, а затем ненадолго меняем текст кнопки и очищаем поле ввода после успешного завершения операции копирования.

Будущее API Clipboard

Рассматриваемое API описывает более общие методы write и read , позволяющие работать с данными, отличающимися от обычного текста, в частности — с изображениями. Например, использование метода read может выглядеть так:

navigator.clipboard.read().then((< items >) => < items.forEach(item =>< console.log(item.type); // делаем что-то с полученными данными >); >);

Обратите внимание на то, что эти методы пока не поддерживаются ни одним из существующих браузеров.

Проверка возможностей браузера

Предположим, вы создали веб-проект, некоторые функции которого полагаются на возможности по работе с буфером обмена. Учитывая то, что API Clipboard в настоящий момент поддерживает лишь один браузер, в подобном проекте нелишним будет предусмотреть альтернативные способы работы с буфером обмена. Например — метод, основанный на execCommand . Для того чтобы понять, поддерживает ли браузер то, что нам нужно, можно просто проверить наличие объекта clipboard в глобальном объекте navigator :

if (navigator.clipboard) < // поддержка имеется, включить соответствующую функцию проекта. >else < // поддержки нет. Придётся пользоваться execCommand или не включать эту функцию. >

Итоги

Полагаем, унифицированный механизм работы с буфером обмена — это полезная возможность, поддержка которой в обозримом будущем появится во всех основных браузерах. Если данная тема вам интересна — взгляните на этот материал Джейсона Миллера.

Уважаемые читатели! Какие варианты использования API Clipboard кажутся вам самыми перспективными?

Источник

How to Copy Text to the Clipboard with JavaScript

Joel Olawanle

Joel Olawanle

How to Copy Text to the Clipboard with JavaScript

When you’re building advanced web pages and applications, you’ll sometimes want to add the copy feature. This lets your users simply click a button or icon to copy text rather than highlighting the text and clicking a couple of buttons on the keyboard.

This feature is mostly used when someone needs to copy an activation code, recovery key, code snippet, and so on. You can also add functionalities like an alert or text on the screen (which could be a modal) to inform the user that the text has been copied to their clipboard.

Previously you would’ve handled this with the document.execCommand() command, but that is deprecated (no longer recommended). You can now use the Clipboard API, which allows you to respond to clipboard commands (cut, copy, and paste) and asynchronously read from and write to the system clipboard.

In this article, you will learn how to write (copy) text and images to the clipboard with the Clipboard API.

In case you are in a rush, here is the code:

Hello World

If you are not in a rush, let’s understand more about the Clipboard API and see how this works with a demo project.

How to Check the Browser’s Permissions

It is important to know that the Clipboard API is only supported for pages served over HTTPS. You should also check for browser permissions before attempting to write to the clipboard to verify if you have the write access. You can do this with the navigator.permissions query:

navigator.permissions.query(< name: "write-on-clipboard" >).then((result) => < if (result.state == "granted" || result.state == "prompt") < alert("Write access granted!"); >>); 

How to Copy Text to the Clipboard

To copy text with the new Clipboard API, you will use the asynchronous writeText() method. This method accepts only one parameter — the text to copy to your clipboard. This can be a string, a template literal holding variables and other strings, or a variable used to hold a string.

Since this method is asynchronous, it returns a promise. This promise is resolved if the clipboard has been updated successfully, and is rejected otherwise:

navigator.clipboard.writeText("This is the text to be copied").then(() => < console.log('Content copied to clipboard'); /* Resolved - text copied to clipboard successfully */ >,() => < console.error('Failed to copy'); /* Rejected - text failed to copy to the clipboard */ >); 

You can also use async/await alongside try/catch:

async function copyContent() < try < await navigator.clipboard.writeText('This is the text to be copied'); 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 */ >> 

Copy text to clipboard example

Here is a demo showing how it works using a real-life example. In this example, we’re fetching quotes from a public quote API. Then when you click the copy icon, the quote and its author get copied, showing that you can adjust what you copy into the writeText() method.

See the Pen copy text JS by Olawanle Joel (@olawanlejoel) on CodePen.

Wrapping Up

In this article, you have learned how to copy text to the clipboard with JavaScript using the Clipboard API without having to think outside the box or install any JavaScript library.

Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.

Источник

Читайте также:  Deserialize json to object java gson
Оцените статью