I'm creating a small site to generate amazon affiliate link using asin I used a small script to generate the URL but I'm looking to copy the output in the clipboard directly.
I looked around without finding a suitable solution for my problem.
Here is the script I'm using to generate the URL.
The HTML part is just an input and a button.
<script>
function myFunction() {
let userInput = document.querySelector("#userInput");
let url = document.querySelector("#url");
url.innerHTML = "https://www.amazon.it/dp/" userInput.value "/ref=nosim?tag=altpe-21";
}
</script>
CodePudding user response:
If you want a simple solution you'll have to create another function once the link is already created and up in the website.
The new function will use the document.getElementById()
function and the .select()
method
example and implementation can be found here:
https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
CodePudding user response:
You can use the Clipboard
API in the navigator
for this purpose.
<script>
function myFunction() {
let userInput = document.querySelector("#userInput");
let url = document.querySelector("#url");
let output = "https://www.amazon.it/dp/" userInput.value "/ref=nosim?tag=altpe-21";
url.innerHTML = output;
navigator.permissions.query({name: "clipboard-write"}).then(result => {
if (result.state == "granted" || result.state == "prompt") {
navigator.clipboard.writeText(output);
}
});
}
</script>
CodePudding user response:
Here is the simple solution:
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
navigator.clipboard.writeText(copyText.value);
/* Alert the copied text */
alert("Copied the text: " copyText.value);