I have web application, which is mostly designed to be run on mobile devices. I have one button, which will copy to device clipboard the passed text. I am using javascript for that. My code is working great on all mobile devices, except for iphone and ipad. Anybody knows what can be the problem? Here is my code:
CopyToClipboard = function(text, fallback){
var $t = $('<textarea />');
$t.val(text).appendTo('body');
$t.select();
document.execCommand('copy');
$t.remove();
return true;
};
I have also tried to go this way, but no result, still not working on iphone
function detectIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// IE 12 => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser
return false;
}
function copytext(text) {
if (detectIE()) {
window.clipboardData.setData('Text', text);
}
var textField = document.createElement('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
document.execCommand('copy');
window.clipboardData.setData('Text', copytext);
textField.remove();
}
function copytext(text) {
var textField = document.createElement('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
document.execCommand('copy');
$(textField).remove();
}
According to CanIUse, Safari on iOS doesn't support
document.execCommand('copy')
, probably because of security reasons.Try this. Works for me.