Search code examples
javascriptcolorsuiwebviewfont-face

Javascript Text Editor in UIWebView using execCommand


Why can't the following javascript command set the font color in RGB hex used in a UIWebView html rich text editor ?

Colors in RGB hex are changed to the standard blue, yellow, red, etc, for example:

[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.execCommand('forecolor', false, '#407ec9')"]];

generates in html

<font color="#0000ff"> HELLO WORLD </font>

Solution

  • Solved it. This is my workaround answer:

    NSString *color = @"#407ec9";
    NSString *text = [self.webView stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"];
    
    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.execCommand('insertHTML', false, '%@')", [NSString stringWithFormat:@"<font color=\"%@\">%@</font>", color, text]]];