0

I am trying to make a copy button, where If I click on the button it will copy the current browser URL and will show an alert that the URL copied.

I tried this

<a id="copy" href="javascript:void(0);"><i onclick="myFunction()" class="fa fa-files-o" aria-hidden="true"></i></a>

<script>
var url = window.location.href;
function myFunction() {
    
  return navigator.clipboard.writeText(url);
  
  // Alert the copied text
  alert("Copied the URL: " + url);
 }
 
</script>

Here the alert is not working, where I am making mistake?

I tried this, It's working on the Desktop but in mobile, only the alert function is executing, and myFunction() is not executing.

<a id="copy" href="javascript:void(0);"><i onclick="myFunction();,alertUrl();" class="fa fa-files-o" aria-hidden="true"></i></a>

<script>
var url = window.location.href;
function myFunction() {
    
  return navigator.clipboard.writeText(url);

 }
 function alertUrl(){
  
  // Alert the copied text
  alert("Copied the URL: " + URL);
 }
</script>

2 Answers2

2

When you return your function exits, so alert is never invoked.

// nothing after this "return" in your function
// will execute because "return" exits your function.

return navigator.clipboard.writeText(url);
ray
  • 26,557
  • 5
  • 28
  • 27
  • Is there any way to both alert and return? – Mohammad Fathi Rahman Nov 04 '22 at 06:05
  • 1
    @MohammadFathiRahman You can do the alert before the return, but JS alert is synchronous. So it'll completely block script execution until the user closes the alert. There are ways around that, but it's probably more user friendly to use a modal instead of an alert. You'd also avoid synchronous issues with that. – icecub Nov 04 '22 at 06:15
  • @icecub Thanks, I first executed return function and then alert, it's working on desktop but not working in mobile, I have updated the question with code. – Mohammad Fathi Rahman Nov 04 '22 at 06:21
0

Solved, After Mad7Dragon's comment

you can check my answer to a similar question here but instead of text, put current page URL

<a id="copy" href="javascript:void(0);"><i onclick="copyURL()" class="fa fa-files-o" aria-hidden="true"></i></a>

<script>
var url = window.location.href;

function copyURL() {

navigator.clipboard.writeText(url).then(() => {
  alert("Copied the URL: " + url);
}, () => {

  try {

    window.prompt("Please copy this url", url);

  } catch (error) {
    
    alert("Your browser doesn't support this function");
  }
  
});
}

</script>