Use NSFontPanel to change foreground and background color of text in WebView

190 Views Asked by At

The app:

I have a Mac app in the Mac App Store with an embedded WebView. The WebView contains a contenteditable DIV acting as a rich text editor.

Goal:

I'd like to change the foreground and background color of the selected text inside the WebView via the NSColorWellNSColorPanel mechanism.

Problem:

When I click on a color in the NSColorPanel, NSColorPanel automatically invokes changeColor: on the first responder.

The first responder happens to be a private WebKit class representing my contenteditable DIV: WebHTMLView.

The above mechanism ALWAYS changes the foreground color of the selected text. I need a way to decide if the foreground OR background color should be changed.

Ideal solution:

It would be great if NSColorPanel and NSColorWell could be configured to not automatically call changeColor: on the first responder and let my code handle the color change.

Tried and failed:

1

There are 1 best solutions below

1
On

To intercept changeColor:, set editingDelegate of the web view and implement WebEditingDelegate method webView:doCommandBySelector:.

for example:

- (BOOL)webView:(WebView *)webView doCommandBySelector:(SEL)selector {
    if (selector == @selector(changeColor:)) {
        if (self.foregroundColorWell.active)
            return NO;
        return YES;
    }
    return NO;
}