简体   繁体   中英

Create 'Automatic copy to clipboard' javascript

I want a page to copy some preset text to the clipboard for a user on load.

 function myFunction() { var copyText = document.getElementById("myInput"); copyText.select(); copyText.setSelectionRange(0, 99999) document.execCommand("copy"); alert("Copied the text: " + copyText.value); console.log(copyText.value) } function myClick() { document.getElementById("myButton").click(); }
 <body onload="myClick()"> <input type="text" value="COPIED" id="myInput"> <button onclick="myFunction()" id="myButton">Copy text</button> </body>

The alert appears and the console logs the value - COPIED

But the text isn't actually copied to the clipboard. Clicking on the button 'Copy text' - does work?

You can't put something in the user's clipboard except in response to an overt action of theirs — for instance, a button click. Think about it: You put something in your clipboard, browse a web page, and then click paste and something completely unexpected gets pasted. That's not okay, so browsers don't let you do it.

In a comment you've asked:

Can I ask for permission onload?

The recent asynchronous clipboard API is associated with the "clipboard-write" permission . For instance, this code works on page load when I run it from a secure context :

navigator.permissions.query({name: "clipboard-write"})
.then(({state}) => {
    console.log(`permission response: ${state}`);
    if (state === "granted") {
        const data = [new ClipboardItem({ "text/plain": new Blob([`The time is ${new Date()}`], { type: "text/plain" }) })];
        navigator.clipboard.write(data).then(
            () => {
                console.log("Clipboard write succeeded");
            },
            () => {
                console.error("Clipboard write failed");
            }
        );
    }
});

I'm slightly unhappy to see that neither Brave nor Chrome prompts me to grant the permission. Oddly, as far as I can tell, I have them configured to ask me when applications want access to the clipboard, but I don't get any prompt. Seems like a Chromium bug.


<opinion>
As a user, I would be very cross if a website wrote to my clipboard under any circumstances other than me clicking a button clearly labelled "Copy to clipboard" or similar. It would likely make me never visit that site again.
</opinion>

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