Skip to content

Use navigator.clipboard API #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions src/js/components/CopyToClipboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react';

import { toType } from './../helpers/util';

//clibboard icon
//clipboard icon
import { Clippy } from './icons';

//theme
Expand All @@ -25,21 +25,33 @@ export default class extends React.PureComponent {
}
}

copyToClipboardFallback = (textToCopy) => {
const textArea = document.createElement('textarea');
textArea.value = textToCopy;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}

handleCopy = () => {
const container = document.createElement('textarea');
const { clickCallback, src, namespace } = this.props;

container.innerHTML = JSON.stringify(
const textToCopy = JSON.stringify(
this.clipboardValue(src),
null,
' '
);

document.body.appendChild(container);
container.select();
document.execCommand('copy');

document.body.removeChild(container);
if (navigator.clipboard) {
navigator.clipboard.writeText(textToCopy).catch(() => {
// Fallback for non-secure contexts (i.e. http)
this.copyToClipboardFallback(textToCopy);
});
} else {
// Fallback for old browsers and test environments
this.copyToClipboardFallback(textToCopy);
};

this.copiedTimer = setTimeout(() => {
this.setState({
Expand Down
Loading