Javascript Copy To Clipboard on safari?

前端 未结 7 929
执念已碎
执念已碎 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:06

    now after 4 years of this question,

    safari added Clipboard API !

    you can write & read texts and any arbitrary data to clipboard on safari (in iOS from v13.4 & desktop v13.1 onwards) .

    MDN docs about Clipboard : The Clipboard interface implements the Clipboard API, providing—if the user grants permission—both read and write access to the contents of the system clipboard. The Clipboard API can be used to implement cut, copy, and paste features within a web application.

    This is how you can achieve what you want:

    navigator.clipboard.writeText("YOUR_TEXT").then(function() {
    
      /* clipboard successfully set */
    
    }, function() {
    
      /* clipboard write failed */
    
    });
    
    0 讨论(0)
  • 2020-12-10 03:09

    I found that for safari the text needs to be selected before document.execCommand() works.

    Also, addRange() is not supported for other browsers (deprecated in Chrome), which means there are instances that it doesn't properly merge the selection and the range together. What this means for user experience was the user would need to click twice in Safari for the value to be copied. Adding .removeAllRanges() before adding the range will help make sure you are grabbing the right selection for the copy. Unclear if you still need the second .removeAllRanges() but I kept it to be safe.

     copy(id) {
        var configId = document.querySelector(id);
        var range = document.createRange();
        range.selectNode(configId);
        var selection = window.getSelection()
        selection.removeAllRanges();
        selection.addRange(range);
    
        try {
          var successful = document.execCommand('copy');
          var msg = successful ? 'successful' : 'unsuccessful';
          console.log('Copy command was ' + msg);
        } catch (err) {
          console.log('Oops, unable to copy');
        }
    
        selection.removeAllRanges();
      }
    

    To use (within same class):

    <Button icon="copy" onClick={() => {this.copy(id)}}/>
    

    id could be any html selector

    This has worked for me in Chrome and Safari.

    0 讨论(0)
  • 2020-12-10 03:11

    Because the first answer doesn't work for me on iPhone 10 Safari I have tried to find an other solution and I found one described here

    Basically it says a very similar solution but different syntax:

    supported by "IE 10+, Chrome 43+, Firefox 41+, and 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;
    }
    <p>Email me at <a class="js-emaillink" href="mailto:chriscoyier@gmail.com">chriscoyier@gmail.com</a></p>
    
    <p><button class="js-emailcopybtn">Copy Email</button></p>

    It also mentions a lib called clipboardjs what just looks great.

    In my case this simple js code works on:

    • iPhone 10 Safari
    • chrome (android / pc (67.0.3396.79))
    • opera (pc (53.0.2907.68))

    Unfortunately it doesn't work:

    • pc / android Firefox (60.0.1 (64-bit))

    In case of Firefox the simple select and copy does the trick.

    element.select();
    document.execCommand('copy');
    
    0 讨论(0)
  • 2020-12-10 03:13

    I had the same problem - it turned out my issue was caused because I was creating a temporary select element to copy the text from, which is fine, but I was also hiding it via various methods, the culprit being element.style.width = 0. Removing that and using other methods to hide it solved my issue.

    Hope this helps anyone running into the same problem.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 03:16

    According to CanIUse, Safari on iOS doesn't support document.execCommand('copy'), probably because of security reasons.

    0 讨论(0)
提交回复
热议问题