Make clipboard copy-paste work on iphone devices

2019-02-14 01:58发布

问题:

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();
}

回答1:

Try this. Works for me.

var copy = function(elementId) {

	var input = document.getElementById(elementId);
	var isiOSDevice = navigator.userAgent.match(/ipad|iphone/i);

	if (isiOSDevice) {
	  
		var editable = input.contentEditable;
		var readOnly = input.readOnly;

		input.contentEditable = true;
		input.readOnly = false;

		var range = document.createRange();
		range.selectNodeContents(input);

		var selection = window.getSelection();
		selection.removeAllRanges();
		selection.addRange(range);

		input.setSelectionRange(0, 999999);
		input.contentEditable = editable;
		input.readOnly = readOnly;

	} else {
	 	input.select();
	}

	document.execCommand('copy');
}
<input type="text" id="foo" value="text to copy" />
<button onclick="copy('foo')">Copy text</button>



回答2:

According to CanIUse, Safari on iOS doesn't support document.execCommand('copy'), probably because of security reasons.