Since iOS 14 WebKit supports findString, but there is no documentation whatsoever yet.
However on the WWDC Sessions Discover WKWebView enhancements they mention that is a basic functionality for "Find on Page", where you can find a string and the WebView will select it and scroll to center it.
It seems very easy to use and to be finding the string as I get a result of matchFound true, but there is no selection and there is no scrolling. Maybe I'm missing something?
This is the code I have tried:
let webView = WKWebView()
// ...
// after loading a website with the desired string on it.
// ...
webView.find("hello world") { result in
print(result.matchFound) // true
}
On iOS 16 we have the new UIFindInteraction API and now it is possible and very easy to do a Find on Page feature and search for a string.
myWebView.isFindInteractionEnabled = true
myWebView.findInteraction?.presentFindNavigator(showingReplace: false)
UIFindInteraction is not supported on macOS.
Refer to this answer to use NSTextFinder instead: https://stackoverflow.com/a/79759860/4691224
So far I was only able to make it 'kind of working' combining with a bit of JavaScript.
let webView = WKWebView()
webView.select(nil)
webView.find("hello world") { result in
guard result.matchFound else { return }
webView.evaluateJavaScript(
"window.getSelection().getRangeAt(0).getBoundingClientRect().top") { offset, _ in
guard let offset = offset as? CGFloat else { return }
webView.scrollView.scrollRectToVisible(
.init(x: 0,
y: offset + webView.scrollView.contentOffset.y,
width: 100,
height: 100), animated: true)
}
}
Description:
1.
webView.select(nil) to make it first responder.
This is important otherwise when the match is found it won't be selected.
2.
webView.find("my string")
3.
If match is found use JavaScript to get the offset to the selected text.
4.
When receiving the offset scroll to it.