简体   繁体   中英

Copy to clipboard HTML

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>

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

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>

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM