如何使用纯javascript将字符串保存在剪贴板中



我想制作一个bookmarklet来保存从数组解析的字符串,我正在寻找一种简单的方法来将我的const cp = 'text'保存到剪贴板中。这个问题有什么解决办法吗?提前感谢:(

发帖前先四处看看。这来自w3schools网站。那里有很多很棒的解释。https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

function myFunction() {
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}

我使用了以下函数来实现这一点。

const copyToClipboard = (e) => {
const el = document.createElement('input')
el.value = window.location // I need a string that was located in the url => you should use whatever value you need, and set the input value to that, obviously.
el.id = 'url'
el.style.position = 'fixed'
el.style.left = '-1000px' // otherwise, sometimes, it creates an input element visible on the screen
el.setAttribute('readonly', true) // to prevent mobile keyboard from popping up
document.body.appendChild(el)
el.select()
document.execCommand('copy')
}

您可以使用复制事件创建这样的函数

const copyToClipboard = (text) => {
document.addEventListener('copy', function(e) {
e.clipboardData.setData('text/plain', text);
e.preventDefault();
});
document.execCommand('copy');
}

这个答案也很有帮助。

最新更新