From b794b7d860ab250946cc9f52f6fb866cd0f9611d Mon Sep 17 00:00:00 2001 From: Alex Bomko Date: Fri, 12 Jul 2024 19:37:34 -0500 Subject: [PATCH] A fix for CopyToClipboard functionality that does not work ### Fix CopyToClipboard Functionality #### Issue: The `CopyToClipboard` functionality does not work in Chrome Version 126.0.6478.127 (Official Build) (arm64), with no error messages provided. #### Root Cause: The `execCommand` function, which was previously used for copying text to the clipboard, is deprecated and no longer recommended as per [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand). This deprecation affects its reliability and compatibility across browsers. #### Solution: To address this issue, the fix implements a conditional approach: - **Primary Method:** Use the new [Clipboard API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard#browser_compatibility) if it is available. This API is more modern and secure, though not fully supported in all environments. - **Fallback Method:** If the Clipboard API is not supported, the function falls back to using `execCommand` to maintain compatibility with older browsers. #### Changes: - Added a check for Clipboard API availability. - Implemented the Clipboard API for copying text when supported. - Retained `execCommand` as a fallback to ensure broad compatibility. This approach ensures that the `CopyToClipboard` functionality works reliably across a range of browsers and versions, improving user experience and adhering to current web standards. --- src/js/components/CopyToClipboard.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/js/components/CopyToClipboard.js b/src/js/components/CopyToClipboard.js index 62ea78d..ab19457 100644 --- a/src/js/components/CopyToClipboard.js +++ b/src/js/components/CopyToClipboard.js @@ -37,7 +37,12 @@ export default class extends React.PureComponent { document.body.appendChild(container); container.select(); - document.execCommand('copy'); + + if (navigator.clipboard && navigator.clipboard.writeText && typeof navigator.clipboard.writeText === "function") { + navigator.clipboard.writeText(container.value); + } else { + document.execCommand("copy"); + } document.body.removeChild(container);