gitmyhub

WebViewJavascriptBridge

Objective-C ★ 14k updated 1y ago

An iOS/OSX bridge for sending messages between Obj-C and JavaScript in UIWebViews/WebViews

Small iOS and macOS library that lets native Objective-C code and in-app web page JavaScript call each other by registering named message handlers.

Objective-CCocoaPodssetup: moderatecomplexity 3/5

This is a small library for Apple's iOS and macOS apps that lets two parts of an app talk to each other. Many apps show web pages inside a panel called a web view. The native side of the app is written in Objective-C, while the page inside the web view runs JavaScript. Normally these two sides cannot easily call each other. This library acts as a bridge so messages can be sent in both directions. It supports the older UIWebView and WebView components as well as the newer WKWebView.

The README lists companies and apps that have used it, including Facebook Messenger and Facebook Paper, presented as a small and incomplete sample. You add the library either through CocoaPods, a popular dependency manager for Apple projects, or by dragging its folder into your project by hand.

The core idea is handlers. On the Objective-C side you register a named handler, for example one called ObjC Echo, and provide a block of code to run when it is called. The JavaScript side can then call that handler by name and optionally receive a response. The same works in reverse: JavaScript registers named handlers, and the Objective-C code calls them. Each call can carry data and an optional response callback, so one side can send a value and get an answer back. To set this up, the page must paste in a short setup function that the README provides.

The documentation also covers a migration note for upgrading between major versions, a reminder that the library depends on Automatic Reference Counting, and a reference list of the methods available on both sides. There is also an unsafe option to speed up message passing by skipping a timing safety check, which the README warns against using if your JavaScript shows alert or confirm popups.

Where it fits