1

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>
Script: http://jsfiddle.net/6n10y0ds/9/

1 Answer 1

3

The problem is because getAsString() is asynchronous, therefore you're attempting to read c before the value has been set.

To fix this extract the logic dependant on c in to its own function and call that function in the callback of getAsString():

$('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);
      doStuff(text);
    });
  } else {
    if (dt && ('getData' in dt)) {
      $('.log').text(dt.getData('text'));
      doStuff(dt.getData('text'));
    }
  }
});

function doStuff(foo) {
  console.log('You pasted', foo);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  Pasted text: <span class="log"></span>
</p>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.