I'm trying to intecept a paste event inside a webpage (it doesn't matter where I paste, i need to intercept also outside an input field so I set BODY for the event)
This is a code found somewhere here. I modified it to put the pasted content inside a variable c for other purposes, but i don't know how, it result always empty.
How can I fix this? Or... is there a jquery plugin better compatibles with ALL browsers?
$('body').on('paste', function(e) {
var c = "";
var dt = e.originalEvent.clipboardData;
if (dt && dt.items && dt.items[0]) {
dt.items[0].getAsString(function(text) {
$('.log').text(text);
c = text;
});
} else {
if (dt && ('getData' in dt)) {
$('.log').text(dt.getData('text'));
c = dt.getData('text');
}
}
console.log(c); //<-- always empty
// do some stuff with my "c" variable
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Pasted text: <span class="log"></span>
</p>