我正在使用一个隐藏的文本区域来放置一些文本,选择它,然后使用document.execCommand将其复制到剪贴板。通常这样做可以成功,但当文本很大时会失败(返回false)。在Chrome v55中,它似乎在大约180K个字符左右就会失败。
这种方式可以复制的数据量是否有限制?普通的Ctrl+C似乎不受相同的限制。
注意:有人将此标记为可能是Does document.execCommand('copy') have a size limitation?的重复问题。虽然这可能是类似的问题,但那个问题被标记为一个我不使用的特定框架,并且还没有得到解答。我认为我的问题更加普遍且仍然相关。
我附上参考代码。
function copyTextToClipboard(text) {
var textArea = document.createElement('textarea');
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = 0;
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}