2

I can't seem to get the execCommand for cut, copy, paste to work in a UIWebView that has contentEditable set to true. I am able to select the text using selectAll command but cut, copy, and paste do not work.

This is the code I'm using:

[webView stringByEvaluatingJavaScriptFromString:@"document.execCommand('cut', false, null)"];

Is there something else I need to do to allow clipboard operations to work?

Firefly
  • 282
  • 5
  • 13

2 Answers2

6

As per previous comments cut, copy, paste commands don't appear to work so I managed to achieve the same operations like so:

- (void)cut
{
    NSString *selection = [self.webView stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"];
    [webView stringByEvaluatingJavaScriptFromString:@"document.execCommand('delete', false, null)"];
    [UIPasteboard generalPasteboard].string = selection;
}

- (void)paste
{
    NSString *text = [UIPasteboard generalPasteboard].string;
    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.execCommand('insertHTML', false, '%@')", text]];
    [UIPasteboard generalPasteboard].string = @"";
}
Firefly
  • 282
  • 5
  • 13
  • Hi Firefly, your answer is good. Bt if i copy text which has some bold and some simple, then this doesn't work. – iBhavik Aug 26 '13 at 09:35
  • I haven't tried this but the code from this post might work: http://stackoverflow.com/questions/4176923/html-of-selected-text - You could then replace window.getSelection() with window.getSelectionHtml(). This should retain the string attributes but you probably need to do some extra work to make it work alright. – Firefly Sep 07 '13 at 01:30
1

I'm not 100% sure, but I don't believe it is possible to invoke cut, copy, or paste programmatically in a UIWebView. You can, however get the selected text, using window.getSelection(). You can do what you want with the selection from there.

mattsven
  • 22,305
  • 11
  • 68
  • 104
  • That a bit of a shame because selectAll command works nicely and selects the text auto-magically just like it does in a UITextView with the blue highlighting, etc. – Firefly May 18 '13 at 08:18
  • Well, then why do you need the other functions? If you can select all text, you can get that selected text using JavaScript. – mattsven May 18 '13 at 08:21
  • Because I wanted the cut command to actually remove the text like it normally would in native iOS controls. I managed to find a solution which does the job. Thanks for pointing in the right direction! – Firefly May 18 '13 at 08:42