0

Html button code as follows i tried simple onclick function on button and also event on second button

<button onclick="myFunction()">Click me</button>
<button id="button">Paste</button>

Javacript code as follows

function myFunction() {

      var clipboarddata =  window.event.clipboardData.getData('text');    
      console.log("paste value" + clipboarddata);
}

var button = document.getElementById("button");
button.addEventListener("click", function(event){
   alert(event.target);
   event.preventDefault();
   var clipboarddata =  window.event.clipboardData.getData('text');    
   console.log("paste value" + clipboarddata);
});

both the ways i am getting same error

JSS
  • 21
  • 1
  • 12
  • Did you mean `event.clipboardData`? Which browser? Browser support of clipboards is not uniform. – Tim Roberts May 16 '23 at 02:57
  • [`window.event`](//developer.mozilla.org/en/docs/Web/API/Window/event) is deprecated. – Sebastian Simon May 16 '23 at 02:59
  • Every browser i am getting- cannot read properties of undefined (reading 'getData') at HTMLButtonElement. – JSS May 16 '23 at 03:02
  • $(document).ready(function(){ $("#main").on("paste",function(event){ event.preventDefault(); var clipboarddata = window.event.clipboardData.getData('text'); console.log("paste value" + clipboarddata); $('#pasteData').text(clipboarddata); }); }); – JSS May 16 '23 at 03:03
  • with above i tried it is working but on button click function i am not able to do it – JSS May 16 '23 at 03:03
  • may be i am using jquery for this clipboard API that is why it is working on paste event function but on buttonclick i am having simple function in javascript but i want this to work on buttonclick in javascript – JSS May 16 '23 at 03:10
  • @SSJ jQuery is irrelevant. Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. Then use the `event` parameter. – Sebastian Simon May 16 '23 at 03:10

1 Answers1

0

You can use navigator.clipboard.readText instead.

<button id="button">Paste</button>
<script>
document.querySelector('#button').addEventListener('click', e => {
  navigator.clipboard.readText().then(text => console.log("paste value:", text));
});
</script>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80