How to change the text selection color in WKWebView?

Viewed 2750

I'm trying to change text selection color in WKWebView. I tried pretty much all the solutions proposed for UIWebView/WKWebView that I was able to find.

Changing tint color does not work. Applying css for ::selection, -webkit-tap-highlight-color tags works neither.

enter image description here

It's always blue. Is it possible to change it?

3 Answers

Here's the sample code for it.

function highlight(colour) {
var range, sel;
if (window.getSelection) {
    // IE9 and non-IE
    try {
        if (!document.execCommand("BackColor", false, colour)) {
            makeEditableAndHighlight(colour);
        }
    } catch (ex) {
        makeEditableAndHighlight(colour)
    }
} else if (document.selection && document.selection.createRange) {
    // IE <= 8 case
    range = document.selection.createRange();
    range.execCommand("BackColor", false, colour);
}}

call this method by Objective-C code

[webView stringByEvaluatingJavaScriptFromString:@"highlight('#ff0')"];

As of iOS 13, setting WKWebView's tintColor property also changes the selection color (and the caret color).

WKWebView *webView = ...
webView.tintColor = UIColor.redColor;

Extra tip: if you have an app that has dark mode support but for some reason the WKWebView content must be light mode, you can either force the whole view controller containing the WKWebView to have the light mode trait or you can do:

if (@available(iOS 13.0, *)) {
    webView.tintColor = [webView.tintColor resolvedColorWithTraitCollection:[UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleLight]];
}

this ensures that the selection and caret colors will be visible with "light" content in the html

Related