3

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!

Risky leopard
  • 91
  • 2
  • 8

4 Answers4

2

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 (i.e. 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>
Jarrod McGuire
  • 523
  • 5
  • 11
  • Yes, @jarrod i also know that, but i asked this question because i want to know that any other way to fix it. – Risky leopard Feb 18 '19 at 10:51
  • @Riskyleopard, I have updated my post because I found something very strange happening, but I think (if it is actually working, and not some quirk on my machine) it would be a total hack and might be a bug in Chrome or something like that. I think in general that there is no real way to "fix" this problem because it isn't broken, it's by design. And anything that gets around it will likely be patched at some point in the future. – Jarrod McGuire Feb 18 '19 at 11:40
  • Just to follow up: I did some testing, and the navigator version hack only works on page load for Chrome versions 71-73. 74 dev build did what I would have expected i.e. didn't work on page load. – Jarrod McGuire Feb 18 '19 at 14:53
1

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

Sagar Agrawal
  • 639
  • 1
  • 7
  • 17
0

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

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

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>
James Moberg
  • 4,360
  • 1
  • 22
  • 21