乐闻世界logo
搜索文章和话题

How does WebView interact with native applications? What are the implementation methods?

3月6日 21:26

WebView interaction with native applications can be implemented through the following methods:

  1. JavaScriptInterface (Android):

    • In Android, expose Java objects to JavaScript through addJavascriptInterface method
    • JavaScript can directly call methods of this object
    • Note: Need to use @JavascriptInterface annotation to avoid security vulnerabilities
  2. WKScriptMessageHandler (iOS):

    • In iOS, use addScriptMessageHandler method of WKUserContentController
    • JavaScript sends messages via webkit.messageHandlers.xxx.postMessage()
    • Native receives messages by implementing userContentController:didReceiveScriptMessage: method
  3. URL Scheme:

    • JavaScript initiates URLs with specific formats through window.location.href or iframe.src
    • Native intercepts via shouldOverrideUrlLoading (Android) or decidePolicyForNavigationAction (iOS)
    • Advantage: Good cross-platform compatibility; Disadvantage: URL length limitation
  4. WebMessagePort:

    • Message channel API supported by modern WebView
    • Provides bidirectional communication capability, supports sending complex data
    • More efficient and secure than URL Scheme
  5. File sharing:

    • Implement data exchange through shared files
    • Suitable for large data transmission
  6. Third-party frameworks:

    • Such as React Native's WebView component
    • Cordova/PhoneGap's bridging mechanism
    • Advantage: Encapsulates complex interaction logic, easier to use

The choice of interaction method should be based on comprehensive consideration of specific scenarios, data volume, performance requirements and other factors.

标签:Webview