In Safari, and in an NSTextView on OSX, search results can be highlighted with a bright yellow box that has a little animated pop. Is there any way to do this in a webview without coding it all myself?
How to I highlight search results in a webview like Safari and NSTextView showFindIndicatorForRange:
3 Answers
I did find a way to do this.
-
1showFindIndicatorForRange: is a method of NSTextView. I need this functionality in a WebView. I'm highlighting the text using methods in WebView but I don't have the animation. There is probably a javascript solution but I haven't looked into it.– Mike TAug 25, 2011 at 4:58
-
Maybe not the answer to the original question, but exactly what I was looking for!– DemitriMay 27, 2020 at 20:38
The answer (as of 2013-05) seems to be that you have to highlight the find results in the webview manually (ref: "Implementing a Find menu item like Safari?" thread from 2011), although it's a long-planned webkit feature.
I'll list the links I found while researching this.
- There's HighlightedWebView but at the time of writing it appears to insert
<span>
s to highlight the search terms. - I couldn't find an answer on how to mimic this effect with Core Animation:
- Core animation - Safari Find effect on cocoa-dev has an overview of the solution, but no code
- https://stackoverflow.com/questions/12187511/mimicking-showfindindicatorforrange-with-calayer here on SO has no answers
- On WebView and NSTextFinder (the standard find bar interface):
- How do I get NSTextFinder to show up here on SO is related, but it doesn't seem it's about this exact problem.
- NSTextFinder reference (the "Text View Support for the Find Bar" section) suggests it can draw "the yellow find indicator background bezel" for any NSView/NSScrollView if it supports NSTextFinderClient (which WebView does not - ref.: [1], [2]).
- "WebView find panel/bar implementation" on cocoa-dev is the most recent (2013-04) thread on this and it contains an overview of the possible solution.
Take a look at this open source WebView subclass (MIT License) that incorporates NSTextFinder support:
https://github.com/shc-vj/SHCWebView
as well as the WebKit source itself for its MiniBrowser test app:
https://github.com/WebKit/webkit/blob/master/Tools/MiniBrowser/mac/WK2BrowserWindowController.m
The MiniBrowser's window controller implements NSTextFinderBarContainer so it doesn't have to put its WebView inside an otherwise superfluous scrollview for the find bar to work.