/   Sign up×
Bounties /Pin to ProfileBookmark

In JavaScript, how can I copy an HTML snippet to the clipboard now that execCommand is deprecated?

to post a answer
JavaScript

4 Answer(s)

Copy linkTweet thisAlerts:
@jSiFeb 10.2023 — Check out Clipboard API:
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API

As of writing Clipboard API is supported in most modern browsers (Chrome, Firefox, Edge, etc.) but not Internet Explorer.


async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Text copied to clipboard');
} catch (err) {
console.error('Failed to copy text: ', err);
}
}

const htmlSnippet = 'HTML snippet';
copyToClipboard(htmlSnippet);


Another alternative could be the library Clipboard.js:
https://clipboardjs.com/
Copy linkTweet thisAlerts:
@OnlineDevelopersFeb 12.2023 — async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Text copied to clipboard');
} catch (err) {
console.error('Failed to copy text: ', err);
}
}


In this example, navigator.clipboard.writeText is used to write the specified text to the clipboard. Note that the Clipboard API is asynchronous, so you need to use await when calling writeText. Additionally, the Clipboard API requires the user's permission, so you may need to add logic to request permission if it has not yet been granted.

If you need to support older browsers that don't have the Clipboard API, you can use a combination of the createElement and execCommand methods to create a temporary textarea element and copy its contents to the clipboard. Here's an example:


function copyToClipboard(text) {
var textarea = document.createElement("textarea");
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
}
Copy linkTweet thisAlerts:
@steimeFeb 12.2023 — As of 2021, the execCommand method of the document object has been deprecated and is not recommended for use in new projects. A more modern and recommended method for copying text to the clipboard is to use the Clipboard API.

Here's an example of how you can copy an HTML snippet to the clipboard using the Clipboard API:


const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};

const htmlSnippet = 'This is an HTML snippet.';
copyToClipboard(htmlSnippet);
@buildinteractiveauthorThanks but this seems to still use the execCommand in your demo.Feb 13.2023
@steimeI'm sorry for this. Here is the code with the Clipboard API. Here's an example of how you can copy text to the clipboard without using the execCommand method, using the Clipboard API: const copyToClipboard = async str => { try { await navigator.clipboard.writeText(str); console.log('Text copied to clipboard'); } catch (err) { console.error('Failed to copy text: ', err); } }; const htmlSnippet = 'This is an HTML snippet.'; copyToClipboard(htmlSnippet); In this example, the copyToClipboard function uses the writeText method of the navigator.clipboard object to copy the str argument to the clipboard. Note that the writeText method returns a Promise, so you can use async/await syntax to handle the result. The Clipboard API is supported in modern browsers, but may not be available in older browsers. You may need to provide a fallback solution for these cases. I hope this helps :)Feb 13.2023
@buildinteractiveauthorVery cool, thank you for clarifying.Feb 13.2023
Davinci•003 auto-reply
// Create a hidden textarea element
const textArea = document.createElement('textarea');

// Set the value of the textarea to the HTML snippet
textArea.value = '...';

// Append the textarea to the document
document.body.appendChild(textArea);

// Select the textarea
textArea.select();

// Copy the textarea contents
document.execCommand('copy');

// Remove the textarea
document.body.removeChild(textArea);

Was this helpful?

×

Success!

Help @buildinteractive spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.27,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: sell your code,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @navneet1991,
amount: 1000 SATS,
source: article

tipper: @ringsideikon07,
amount: 100 SATS,
source: article

tipper: @todd,
amount: 1000 SATS,
source: article
)...