Javascript复制到Safari上的剪贴板?
这可能是重复的问题,但我没有找到解决方案。
我想在按钮点击上复制文字。 它在chrome,mozilla上工作(在windows和mac上工作但在linux上工作)。 它没有在safari工作。
我正在使用document.execCommand("copy")
命令进行复制。
safari支持这个命令吗?
有没有什么方法可以支持所有浏览器?
请检查我的解决方案。
它适用于Safari(在iPhone 7和iPad上测试)和其他浏览器。
window.Clipboard = (function(window, document, navigator) { var textArea, copy; function isOS() { return navigator.userAgent.match(/ipad|iphone/i); } function createTextArea(text) { textArea = document.createElement('textArea'); textArea.value = text; document.body.appendChild(textArea); } function selectText() { var range, selection; if (isOS()) { range = document.createRange(); range.selectNodeContents(textArea); selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); textArea.setSelectionRange(0, 999999); } else { textArea.select(); } } function copyToClipboard() { document.execCommand('copy'); document.body.removeChild(textArea); } copy = function(text) { createTextArea(text); selectText(); copyToClipboard(); }; return { copy: copy }; })(window, document, navigator); // How to use Clipboard.copy('text to be copied');
https://gist.github.com/rproenca/64781c6a1329b48a455b645d361a9aa3 https://fiddle.jshell.net/k9ejqmqt/1/
希望对你有所帮助。
问候。
根据CanIUse,iOS上的Safari不支持document.execCommand(’copy’),可能是出于安全原因。
因为第一个答案对我来说在iPhone 10 Safari上不起作用,我试图找到另一个解决方案,我在这里找到了一个
基本上它说一个非常相似的解决方案,但语法不同:
“IE 10 +,Chrome 43 +,Firefox 41+和Opera 29+”支持
var copyEmailBtn = document.querySelector('.js-emailcopybtn'); copyEmailBtn.addEventListener('click', function(event) { // Select the email link anchor text var emailLink = document.querySelector('.js-emaillink'); var range = document.createRange(); range.selectNode(emailLink); window.getSelection().addRange(range); try { // Now that we've selected the anchor text, execute the copy command var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copy email command was ' + msg); } catch (err) { console.log('Oops, unable to copy'); } // Remove the selections - NOTE: Should use // removeRange(range) when it is supported window.getSelection().removeAllRanges(); });
body { padding: 10px; }
Email me at chriscoyier@gmail.com