Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.clipboardData.getData("Text") doesnt 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?

like image 917
Yan Zepth Avatar asked Dec 11 '13 01:12

Yan Zepth


People also ask

Why can't I read data from clipboard in chrome?

Also when user presses a shortcut like F9, we need to do the same. As chrome have restriction in reading clipboard data, we can read data from clipboard only in paste events. In my case I don't have paste event and also can't manually trigger the paste event in chrome.

How to get clipboard data from a user?

In Chrome, for instance, you can get the clipboardData when handling the paste events [ ^ ], But, you must consider asking the user to manually copy/paste the contents. That is a more cross-browser way of doing this job for them.

Is it possible to get clipboard data cross-browser?

Please Sign up or sign in to vote. Please Sign up or sign in to vote. Because that is only supported by IE itself, it is not supported cross-browser. In Chrome, for instance, you can get the clipboardData when handling the paste events [ ^ ],


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'));
});
like image 136
drew hintz Avatar answered Oct 05 '22 14:10

drew hintz


Cross browser method should be

document.addEventListener('paste', function (evt) {
  clipdata = evt.clipboardData || window.clipboardData;
  console.log(clipdata.getData('text/plain'));
});
like image 45
GiorgosK Avatar answered Oct 05 '22 12:10

GiorgosK