简体   繁体   中英

Javascript copy text to clipboard without click any button on page load

I've been trying to copy the Content of a my P tag to my clipboard without any button click.

I tried it work on perfectly button click.Here is my working code for onClick.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
 <p id="p1">Copied..</p>
 <button onclick="copyToClipboard('#p1')" id="ashvin">Copy</button>
</body>
</html>
<script>
 function copyToClipboard(element) {
  console.log('+++++++++++++++++++++++++++++++');
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  var status = document.execCommand("copy");
  if(status){
   console.log("=======done")
  }else{
   console.log("=======error")
  }
  $temp.remove();
 }
</script>

It's working on button click fine, but i want to copy on page load not a click.

Any help would be greatly appreciated. Thanks!

Many document.execCommand methods (like copy) require a user interaction (like a click) because it is considered a security risk to get access to the clipboard (which is system level, not browser level) with automagic methods like what is being asked for. You might need to re-think what you are trying to achieve by copying on page load.

What is the use-case for the above, and perhaps someone can help with your scenario?

[edit] Here's a link that shows your script on codepen. When you "run" the page it should give the "didn't work" output, when you click the button it should give the "worked" output

 <!DOCTYPE html> <html lang="en"> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script> function copyToClipboard(element) { var $temp = $("<input>"); $("body").append($temp); $temp.val($(element).text()).select(); var status = document.execCommand("copy"); if(status){ $("#output").text("worked") }else{ $("#output").text("didn't work") } $temp.remove(); } </script> </head> <body onload="copyToClipboard('#p1')"> <p id="p1">Text to copy on page load, but won't work</p> <button onclick="copyToClipboard('#p1')">Copy the text</button> <p id="output"></p> </body> </html> 

If this is for a local project (ie won't be in the public domain) there are perhaps flags you can set in chrome to override the security risk, but I don't know what they are or if they exist, but might be worth a look.

[updated edit] I am very confused by something. This feels like a total hack, but it is working for me (on glitch.com), so I might stand corrected. I used the native navigator.clipboard.writeText method, and it didn't work either BUT when I was trying both methods side-by-side (in chrome) to test that both wouldn't work, it did work for the "navigator" one. Turns out if I put document.execCommand somewhere before the promise is executed then it seems to work. BUT it doesn't work on codepen or here in the inline scripting engine (might be to do with iframes etc?). Could someone check my sanity please?

  • Doesn't work (for me) inline in this post
  • Doesn't work (for me) in codepen
  • Works (for me) on glitch

 <!DOCTYPE html> <html lang="en"> <head> <script> function copyToClipboard(element) { document.execCommand("copy"); var text = document.querySelector(element).textContent; var output = document.getElementById("output"); navigator.clipboard.writeText(text).then(function() { output.textContent = "worked"; }, function() { output.textContent = "didn't work"; }); } </script> </head> <body onload="copyToClipboard('#p1')"> <p id="p1">Text to copy on page load.</p> <button onclick="copyToClipboard('#p1')"> Click to copy text </button> <p id="output"></p> </body> </html> 

This will not work because the copy command has to be triggered by the user's action. See this post: https://w3c.github.io/editing/execCommand.html#dfn-the-copy-command

I guess this question is a duplicate of: Cannot use `document.execCommand('copy');` from developer console

write the function on document.body.onload() or add event listener. document.body.addEventListener("load", copyToClipboard); or simply

    <body onload=copyToClipboard('#p1')>
     ..
    </body>

Based on some of the discussion here, I figured out how to automatically auto-populate my clipboard with content from the webpage upon page load using a javascript eventListener with DOMContentLoaded event (No jQuery required). NOTE: I'm using Microsoft Edge Dev 105. (I initially shared it here .)

<script>
function autoCopyToClipboard(){
    console.log("init autoCopyToClipboard", new Date);
    document.execCommand("copy");
    var text = document.getElementById("myTextAreaToCopy").value;
    var output = document.getElementById("AHiddenDivToTestCopy");
    navigator.clipboard.writeText(text).then(function(){
        console.log('Copied to clipboard!', new Date);
    }, function(){
        console.log('Unable to copied to clipboard!', new Date);
    });
}
window.addEventListener("DOMContentLoaded", autoCopyToClipboard, false);
</script>

<button type="button" onclick="autoCopyToClipboard()">Manual Copy</button>
<textarea id="myTextAreaToCopy">This is a test text.</textarea>

<div id="AHiddenDivToTestCopy" style="display:none;"></div>

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