Skip to content Skip to sidebar Skip to footer

Make Clipboard Copy-paste Work On Iphone Devices

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

Solution 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');
}
<inputtype="text"id="foo"value="text to copy" /><buttononclick="copy('foo')">Copy text</button>

Solution 2:

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

Post a Comment for "Make Clipboard Copy-paste Work On Iphone Devices"