Skip to content

Commit 18a09e9

Browse files
authored
Use navigator.clipboard API
Fixes issues with `document.execCommand('copy')` which is deprecated. Uses `navigator.clipboard` instead which has [browser compatibility](https://caniuse.com/mdn-api_clipboard_writetext) of +93%. Replaces microlinkhq#37
1 parent 474800a commit 18a09e9

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

src/js/components/CopyToClipboard.js

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import React from 'react';
22

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

5-
//clibboard icon
5+
//clipboard icon
66
import { Clippy } from './icons';
77

88
//theme
@@ -26,20 +26,23 @@ export default class extends React.PureComponent {
2626
}
2727

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

32-
container.innerHTML = JSON.stringify(
31+
const textToCopy = JSON.stringify(
3332
this.clipboardValue(src),
3433
null,
3534
' '
3635
);
3736

38-
document.body.appendChild(container);
39-
container.select();
40-
document.execCommand('copy');
41-
42-
document.body.removeChild(container);
37+
if (navigator.clipboard) {
38+
await navigator.clipboard.writeText(textToCopy);
39+
} else {
40+
console.error(
41+
'react-json-view error:',
42+
'navigator.clipboard not supported by this browser'
43+
);
44+
return;
45+
};
4346

4447
this.copiedTimer = setTimeout(() => {
4548
this.setState({

0 commit comments

Comments
 (0)