Window. clipboardData. getData("Text") Doesn't Work in Chrome

I have this javascript function:

function maxLengthPaste(field,maxChars)
{
    event.returnValue=false;
    if((field.value.length + window.clipboardData.getData("Text").length) > maxChars) {
        field.value = field.value + window.clipboardData.getData("Text").substring(0, maxChars - field.value.length);
        return false;
    }
    event.returnValue=true;
}

The window.clipboardData.getData("Text") doesn't work in Chrome browser Is there any crossbrowser code to substitute it?

2

2 Answers

No, there is no cross-browser support for window.clipboardData. It is only supported by IE. Support for window.clipboardData is generally considered a security issue because it allows every website you visit to read whatever happens to be in your clipboard at the time.

In Chrome, you can read clipboardData when handling paste events:

document.addEventListener('paste', function (evt) {
  console.log(evt.clipboardData.getData('text/plain'));
});
1

Cross browser method should be

document.addEventListener('paste', function (evt) {
  clipdata = evt.clipboardData || window.clipboardData;
  console.log(clipdata.getData('text/plain'));
});
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest