• Stars
    star
    14,252
  • Rank 1,992 (Top 0.05 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 12 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

WebViewJavascriptBridge

Circle CI

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

Migration Guide

When upgrading from v5.0.x to 6.0.x you will have to update the setupWebViewJavascriptBridge javascript snippet. See https://github.com/marcuswestin/WebViewJavascriptBridge#usage part 4).

Who uses WebViewJavascriptBridge?

WebViewJavascriptBridge is used by a range of companies and projects. This is a small and incomplete sample list:

Installation (iOS & OSX)

Installation with CocoaPods

Add this to your podfile and run pod install to install:

pod 'WebViewJavascriptBridge', '~> 6.0'

Manual installation

Drag the WebViewJavascriptBridge folder into your project.

In the dialog that appears, uncheck "Copy items into destination group's folder" and select "Create groups for any folders".

Examples

See the Example Apps/ folder. Open either the iOS or OSX project and hit run to see it in action.

To use a WebViewJavascriptBridge in your own project:

Usage

  1. Import the header file and declare an ivar property:
#import "WebViewJavascriptBridge.h"

...

@property WebViewJavascriptBridge* bridge;
  1. Instantiate WebViewJavascriptBridge with a WKWebView, UIWebView (iOS) or WebView (OSX):
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
  1. Register a handler in ObjC, and call a JS handler:
[self.bridge registerHandler:@"ObjC Echo" handler:^(id data, WVJBResponseCallback responseCallback) {
	NSLog(@"ObjC Echo called with: %@", data);
	responseCallback(data);
}];
[self.bridge callHandler:@"JS Echo" data:nil responseCallback:^(id responseData) {
	NSLog(@"ObjC received response: %@", responseData);
}];
  1. Copy and paste setupWebViewJavascriptBridge into your JS:
function setupWebViewJavascriptBridge(callback) {
	if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
	if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
	window.WVJBCallbacks = [callback];
	var WVJBIframe = document.createElement('iframe');
	WVJBIframe.style.display = 'none';
	WVJBIframe.src = 'https://__bridge_loaded__';
	document.documentElement.appendChild(WVJBIframe);
	setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
  1. Finally, call setupWebViewJavascriptBridge and then use the bridge to register handlers and call ObjC handlers:
setupWebViewJavascriptBridge(function(bridge) {
	
	/* Initialize your app here */

	bridge.registerHandler('JS Echo', function(data, responseCallback) {
		console.log("JS Echo called with:", data)
		responseCallback(data)
	})
	bridge.callHandler('ObjC Echo', {'key':'value'}, function responseCallback(responseData) {
		console.log("JS received response:", responseData)
	})
})

Automatic reference counting (ARC)

This library relies on ARC, so if you use ARC in you project, all works fine. But if your project have no ARC support, be sure to do next steps:

  1. In your Xcode project open project settings -> 'Build Phases'

  2. Expand 'Compile Sources' header and find all *.m files which are belongs to this library. Make attention on the 'Compiler Flags' in front of each source file in this list

  3. For each file add '-fobjc-arc' flag

Now all WVJB files will be compiled with ARC support.

Contributors & Forks

Contributors: https://github.com/marcuswestin/WebViewJavascriptBridge/graphs/contributors

Forks: https://github.com/marcuswestin/WebViewJavascriptBridge/network/members

API Reference

ObjC API

[WebViewJavascriptBridge bridgeForWebView:(WKWebVIew/UIWebView/WebView*)webview

Create a javascript bridge for the given web view.

Example:

[WebViewJavascriptBridge bridgeForWebView:webView];
[bridge registerHandler:(NSString*)handlerName handler:(WVJBHandler)handler]

Register a handler called handlerName. The javascript can then call this handler with WebViewJavascriptBridge.callHandler("handlerName").

Example:

[self.bridge registerHandler:@"getScreenHeight" handler:^(id data, WVJBResponseCallback responseCallback) {
	responseCallback([NSNumber numberWithInt:[UIScreen mainScreen].bounds.size.height]);
}];
[self.bridge registerHandler:@"log" handler:^(id data, WVJBResponseCallback responseCallback) {
	NSLog(@"Log: %@", data);
}];
[bridge callHandler:(NSString*)handlerName data:(id)data]
[bridge callHandler:(NSString*)handlerName data:(id)data responseCallback:(WVJBResponseCallback)callback]

Call the javascript handler called handlerName. If a responseCallback block is given the javascript handler can respond.

Example:

[self.bridge callHandler:@"showAlert" data:@"Hi from ObjC to JS!"];
[self.bridge callHandler:@"getCurrentPageUrl" data:nil responseCallback:^(id responseData) {
	NSLog(@"Current UIWebView page URL is: %@", responseData);
}];

[bridge setWebViewDelegate:(id)webViewDelegate]

Optionally, set a WKNavigationDelegate/UIWebViewDelegate if you need to respond to the web view's lifecycle events.

[bridge disableJavscriptAlertBoxSafetyTimeout]

UNSAFE. Speed up bridge message passing by disabling the setTimeout safety check. It is only safe to disable this safety check if you do not call any of the javascript popup box functions (alert, confirm, and prompt). If you call any of these functions from the bridged javascript code, the app will hang.

Example:

[self.bridge disableJavscriptAlertBoxSafetyTimeout];

Javascript API

bridge.registerHandler("handlerName", function(responseData) { ... })

Register a handler called handlerName. The ObjC can then call this handler with [bridge callHandler:"handlerName" data:@"Foo"] and [bridge callHandler:"handlerName" data:@"Foo" responseCallback:^(id responseData) { ... }]

Example:

bridge.registerHandler("showAlert", function(data) { alert(data) })
bridge.registerHandler("getCurrentPageUrl", function(data, responseCallback) {
	responseCallback(document.location.toString())
})
bridge.callHandler("handlerName", data)
bridge.callHandler("handlerName", data, function responseCallback(responseData) { ... })

Call an ObjC handler called handlerName. If a responseCallback function is given the ObjC handler can respond.

Example:

bridge.callHandler("Log", "Foo")
bridge.callHandler("getScreenHeight", null, function(response) {
	alert('Screen height:' + response)
})
bridge.disableJavscriptAlertBoxSafetyTimeout()

Calling bridge.disableJavscriptAlertBoxSafetyTimeout() has the same effect as calling [bridge disableJavscriptAlertBoxSafetyTimeout]; in ObjC.

Example:

bridge.disableJavscriptAlertBoxSafetyTimeout()

More Repositories

1

store.js

Cross-browser storage for all use cases, used across the web.
JavaScript
13,944
star
2

WebViewProxy

A standalone iOS & OSX class for intercepting and proxying HTTP requests (e.g. from a Web View)
Objective-C
866
star
3

fun

A programming language for the realtime web.
JavaScript
174
star
4

fin

Realtime data layer for web applications
JavaScript
87
star
5

require

javascript module management. brings node's require statement and npm to the browser
JavaScript
59
star
6

node-kafka

NOT MAINTAINED. See below:
JavaScript
43
star
7

std.js

javascript standard library
JavaScript
33
star
8

alderaan

Alderaan uses Bespin to create a TextMate inspired code editor in the browser. In contrast to Bespin, it is intended to be run against your local file system, and has full terminal/command line integration.
JavaScript
13
star
9

Caret-position

Get and set the user's caret/selection on input/textarea elements
JavaScript
13
star
10

old-tags.js

A small, fast & standalone convenience library for building dom.
JavaScript
7
star
11

ui.js

javascript ui
JavaScript
6
star
12

ometa-js

Clone of the ometa-js svn repository
JavaScript
6
star
13

twitter.js

A thin wrapper for the Twitter jsonp API
JavaScript
5
star
14

tinytest.js

Tiny testing framework for the browser
JavaScript
5
star
15

blowtorch

Native <3 Web
Objective-C
4
star
16

fun-go

Some tools for more fun go
Go
4
star
17

dom.js

JavaScript
4
star
18

Focus

realtime, collaborative task management
JavaScript
3
star
19

FunObjc

Fun ObjC
C
3
star
20

js.ui

js.ui provides an idiomatic approach to creating UI code in vanilla JS.
TypeScript
2
star
21

go-tp

Go text processing
Go
2
star
22

git-star

git* - a bunch of common git tasks made less verbose
Shell
2
star
23

tags.js

JavaScript
2
star
24

marcuswest.in

marcuswestin.in
JavaScript
2
star
25

remote-console

JavaScript
1
star
26

invest

JavaScript
1
star
27

monorepo-merge

Import multiple repos into a single mono repo, into custom subfolder paths, while maintaining full commit history for all repos
Shell
1
star
28

oldDogo

JavaScript
1
star
29

tfocus

Old (abandoned) web-based iPhone todo list w/ server
JavaScript
1
star
30

StayAccount

Objective-C
1
star
31

screenlog

Keep a screenshot log of your computer
1
star
32

marcuswestin.com

Abandoned in favor of http://github.com/marcuswestin/marcuswest.in
JavaScript
1
star
33

js-birect

Efficient, scalable and language-agnostic bidirectional realtime messaging with request/response support.
JavaScript
1
star