skip to Main Content

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>

2

Answers


  1. Chosen as BEST ANSWER

    I am answering my own question as i found a clean way to do this. I found a better jQuery library to do this job.

    Just reference this 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" class="btn btn-secondary" 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.


  2. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search