简体   繁体   中英

How do I copy to the clipboard in JavaScript? tell me

i used this code

const copyBtns = [...document.getElementsByClassName('copy')]
  copyBtns.forEach(btn=> btn.addEventListener('click', ()=>{
    content = btn.getAttribute('data-content')
    navigator.clipboard.writeText(content)
    btn.textContent = "تم النسخ"
  }))

copy not working on click in mobile, and it's working with any computer. what is the solution?

I've used this approach in the past for web apps, which uses jQuery to construct a hidden <input> field and copy the text from there. This seems to work well cross-platform, including Android and iOS devices.

const temp = $('<input>');
$('body').append(temp);
temp.val('YOUR STRING HERE').select();
document.execCommand('copy');
temp.remove();

I suspect the reason your code is not working is because the mobile browser does not have access to (or support for) clipboard . Can I Use? is a great resource to determine support for CSS/HTML and other browser APIs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM