0

I am trying to show an element if the user has something copied into the clipboard. I don't need to know the value, but if I can then it would be amazing.

The closest code I found to achieve this is this one below, but it's not working as the value is always empty and not printed in my console.log. Here below the sample:

function myTimer() {
  console.log('Ciao!');
  var tempElement = document.createElement("input");
  tempElement.style.cssText = "width:0!important;padding:0!important;border:0!important;margin:0!important;outline:none!important;boxShadow:none!important;";
  document.body.appendChild(tempElement);
  var jTempEl = $(tempElement);
  jTempEl.val(' ');
  jTempEl.select();
  jTempEl.trigger('paste');
  var text = jTempEl.val();
  console.log('tempElement text', text);
  console.log('tempElement jTempEl', jTempEl);
  document.body.removeChild(tempElement);
}
var myVar = setInterval(myTimer, 5000);

Do you have any idea why the variable text is empty? I copied something so the clipboard is not empty...

Thanks in advance.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Micky
  • 647
  • 1
  • 11
  • 26
  • 1
    Note that jQuery is a library primarily intended for manipulating the DOM. Similarly Angular is an MVC library for dynamic sites. For interacting with the clipboard you need just plain old Javascript. I've re-tagged the question as such – Rory McCrossan Jun 02 '20 at 18:37
  • 2
    Does this answer your question? [Get current clipboard content?](https://stackoverflow.com/questions/6413036/get-current-clipboard-content) – esqew Jun 02 '20 at 18:39
  • Thanks Rory. I didn't know that. – Micky Jun 02 '20 at 18:39
  • It appears in this current iteration, you're trying to trigger a `paste` into an arbitrary element. If this was possible, it would present an incredible security risk. What would stop a malicious site (or, more likely, a malicious script via ad network/etc.) from stealing the contents of my clipboard surreptitiously? – esqew Jun 02 '20 at 18:40
  • Indeed I wish I could only know if the clipboard data is empty or not, so systematically getting only true or false. So I can advise the user – Micky Jun 02 '20 at 18:46
  • @esqew that solved/helped me in develop my use case. Thanks a lot!! – Micky Jun 02 '20 at 18:47

0 Answers0