2

In my vue project, I have a copy-button which should copy an attribute value from data on click:

<span class="btn-action" :class="!data.value.copy ? 'btn-disabled' : 'btn-active'" @click="copyCode(data.item)"><font-awesome-icon :icon="['far', 'copy']" /></span>

and my copyCode function:

copyCode: function(item) {
    // tests if item exists...    
    let copyText = item.code;
    if (navigator && navigator.clipboard) {
       console.log('navigator:', navigator);
       // this works on chrome/firefox 
       navigator.clipboard.writeText(copyText);
    } else {
       console.log('no navigator');
       this.writeTextIOS(copyText);
       }
    }

writeTextIOS: function(str) {
    return new Promise(function(resolve, reject) {
        let success = false;
        function listener(e) {
            e.clipboardData.setData("text/plain", str);
            e.preventDefault();
            success = true;
        }
        document.addEventListener("copy", listener);
        document.execCommand("copy");
        document.removeEventListener("copy", listener);
        success ? resolve() : reject();
    });
},

I found out on safari, there is navigator, but this does not have clipboard property (I could probably check navigator.userAgent as well, but that is not the issure here, since it definately go into else-statement when I am using safari). I got the writeTextIOS function from here: https://gist.github.com/lgarron/d1dee380f4ed9d825ca7 But I only get an Unhandled Promise Rejectio: undefined exception.

So what should I do here. I don't want to use any third-party package like clipboard.js (yet). Is there any "native" solution for my problem?

yangsunny
  • 656
  • 5
  • 13
  • 32
  • Does this answer your question? [Copy to clipboard using Javascript in iOS](https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios) – Heretic Monkey Nov 05 '19 at 15:27
  • Possible duplicate of https://stackoverflow.com/questions/40147676/javascript-copy-to-clipboard-on-safari – Johnson Samuel Nov 05 '19 at 15:29
  • nope, since I don't want to copy anything from DOM, plus I thought document.execCommand('copy') is not supported in safari? – yangsunny Nov 05 '19 at 15:30
  • Have you tried the `document.execCommand('copy')` as explained here: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard#Writing_to_the_clipboard – Coola Nov 05 '19 at 19:25
  • as I said, I am trying to copy a data attribute which is a string, not something from the DOM – yangsunny Nov 06 '19 at 08:11

0 Answers0