Home > Software design >  Copy to clipboard javascript not working in Mobile devices. What is the issue?
Copy to clipboard javascript not working in Mobile devices. What is the issue?

Time:12-19

The following code is not working on Mobile devices. But works on desktops. What is the issue here?

$(document).ready(function()
{
  copy();
})

function copy() {
  var txt = document.getElementById("result");
  navigator.clipboard.writeText(txt.innerText);    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result">copy text</div>

CodePudding user response:

Did you see the Browser Compat?

Compatibility for writetext

If it's not above, try catching the exception:

<script type="application/javascript">

    $(document).ready(function()
    {
      copy();
    })

      function copy() {
      var txt = document.getElementById("result");
      navigator.clipboard.writeText(txt.innerText)
      .then(() => {
        alert("successfully copied");
      })
      .catch(() => {
        alert("something went wrong");
      });
    }
</script>

CodePudding user response:

I am answering my own question as i found a clean way to do this. I found a better Jqery libary to do this job. Just reference below library

https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.4.0/clipboard.min.js

Then the texts that need to copy should go for the "data-clipboard-text"

 <button id="btnCopyToClipboard"  data-clipboard-text="@Model.OutPutText">Copy below text</button>

Then inside a script tag include this

<script type="application/javascript">
                $(function() {
            new Clipboard('#btnCopyToClipboard');
        });
    </script>

That's it. No compatibility issues. The library will do the job.

  • Related