Javascript Copy To Clipboard on safari?

前端 未结 7 950
执念已碎
执念已碎 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: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;
    }

    Email me at chriscoyier@gmail.com

    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');
    

提交回复
热议问题