0%

JS复制文本到剪贴板中的一些问题

测试反馈无法将文本复制到剪贴板中了,但是我的环境 localhost 无法复现这个问题,正式环境 https://www.xxxx.com 也无法复现

查了一下才知道是测试环境是http的ip访问 http://123.123.123.123 ,浏览器限制了 navigator.clipboard 的使用

https://stackoverflow.com/questions/51805395/navigator-clipboard-is-undefined

This requires a secure origin — either HTTPS or localhost (or disabled by running Chrome with a flag). Just like for ServiceWorker, this state is indicated by the presence or absence of the property on the navigator object.

https://developers.google.com/web/updates/2018/03/clipboardapi

This is noted in the spec with [SecureContext] on the interface: https://w3c.github.io/clipboard-apis/#dom-navigator-clipboard

You can check the state of window.isSecureContext to learn if that’s the reason a feature is unavailable. Secure contexts | MDN

And yes, you should set up HSTS to make sure HTTP redirects to HTTPS.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// return a promise
function copyToClipboard(textToCopy) {
// navigator clipboard api needs a secure context (https)
if (navigator.clipboard && window.isSecureContext) {
// navigator clipboard api method'
return navigator.clipboard.writeText(textToCopy);
} else {
// text area method
let textArea = document.createElement('textarea');
textArea.value = textToCopy;
// make the textarea out of viewport
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise((res, rej) => {
// here the magic happens
document.execCommand('copy') ? res() : rej();
textArea.remove();
});
}
}

copyToClipboard("I'm going to the clipboard !")
.then(() => console.log('text copied !'))
.catch(() => console.log('error'));