How to change the text selection color in WKWebView?
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