Skip to content

Commit ef46927

Browse files
authored
Merge pull request microlinkhq#39 from mbtools/patch-1
Use navigator.clipboard API
2 parents 474800a + 86bbd60 commit ef46927

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/js/components/CopyToClipboard.js

Lines changed: 20 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
@@ -25,21 +25,33 @@ export default class extends React.PureComponent {
2525
}
2626
}
2727

28+
copyToClipboardFallback = (textToCopy) => {
29+
const textArea = document.createElement('textarea');
30+
textArea.value = textToCopy;
31+
document.body.appendChild(textArea);
32+
textArea.select();
33+
document.execCommand('copy');
34+
document.body.removeChild(textArea);
35+
}
36+
2837
handleCopy = () => {
29-
const container = document.createElement('textarea');
3038
const { clickCallback, src, namespace } = this.props;
3139

32-
container.innerHTML = JSON.stringify(
40+
const textToCopy = JSON.stringify(
3341
this.clipboardValue(src),
3442
null,
3543
' '
3644
);
3745

38-
document.body.appendChild(container);
39-
container.select();
40-
document.execCommand('copy');
41-
42-
document.body.removeChild(container);
46+
if (navigator.clipboard) {
47+
navigator.clipboard.writeText(textToCopy).catch(() => {
48+
// Fallback for non-secure contexts (i.e. http)
49+
this.copyToClipboardFallback(textToCopy);
50+
});
51+
} else {
52+
// Fallback for old browsers and test environments
53+
this.copyToClipboardFallback(textToCopy);
54+
};
4355

4456
this.copiedTimer = setTimeout(() => {
4557
this.setState({

0 commit comments

Comments
 (0)