Javascript Copy To Clipboard on safari?

前端 未结 7 955
执念已碎
执念已碎 2020-12-10 02:30

It may be duplicate question but i didnt find the solution for this.

I am trying to copy text on button click. Its working on chrome, mozilla(working on on windows a

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 03:15

    Please check my solution.

    It works on Safari (tested on iPhone 7 and iPad) and on other browsers.

    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/

    Hope that helps you.

    Regards.

提交回复
热议问题