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