How to I highlight search results in a webview like Safari and NSTextView showFindIndicatorForRange:

前端 未结 3 937
遇见更好的自我
遇见更好的自我 2021-01-02 12:00

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

相关标签:
3条回答
  • 2021-01-02 12:17

    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.
    0 讨论(0)
  • 2021-01-02 12:39

    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.

    0 讨论(0)
  • 2021-01-02 12:41

    I did find a way to do this.

    See showFindIndicatorForRange:.

    0 讨论(0)
提交回复
热议问题