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()" 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();" 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>
CodePudding user response:
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);
CodePudding user response:
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()" 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>