Reprint to: http://www.cocoachina.com/ios/20150629/12248.html
Translator: @coderyi9
This article is translated from Marcus Westin's Open source Framework Webviewjavascriptbridge's readme, the English original link https://github.com/marcuswestin/WebViewJavascriptBridge.
Webviewjavascriptbridge is a ios/osx bridge for Obj-c and JavaScript to communicate messages through Uiwebviews/webviews. If you like Webviewjavascriptbridge, you may also want to check outwebviewproxy.
Obj-c and JavaScript simply say that Obj-c calls JavaScript is simple and can be webview by stringbyevaluatingjavascriptfromstring: Method calls the JavaScript code, and JavaScript calls Obj-c, through the proxy method of the Web view Shouldstartloadwithrequest: To receive a JavaScript network request to implement the call.
Projects that are using Webviewjavascriptbridge
There are a lot of companies and projects in use Webviewjavascriptbridge. This list is not complete and you can add it at your own discretion.
Installation & Example (IOS & OSX)
First open the example Apps folder. Open the project for iOS or OSX and click Run.
Use Webviewjavascriptbridge in your own project:
1) Drag the Webviewjavascriptbridge folder into your project.
In the dialog box that appears, cancel (I think it should be selected) "Copy items into destination Group's folder" and select "Create groups for any folders"
2) Introduce the header file and declare a property:
#Import "WebViewJavascriptBridge.h" ... @property webviewjavascriptbridge* BRIDGE;
3) Instantiate the Webviewjavascriptbridge and take a UIWebView (IOS) or WebView (OSX):
Self.bridge = [Webviewjavascriptbridge bridgeforwebview:webview handler:^(id data, Wvjbresponsecallback Responsecallback) {NSLog (@"Received message from JavaScript:%@", data); Responsecallback Atcha ");}];
4) First send some messages from OBJC to javascript:
[Self.bridge send:@ "Well hello there"]; [Self.bridge send:[nsdictionary dictionarywithobject:@"Foo" forkey:@ "Bar"]; [Self.bridge send:@"Give me a response, would you?" responsecallback:^(id responsedata) {NSLog (@"OBJC got It S response! %@ ", ResponseData);}];
5) Then, look at the JavaScript side:
function Connectwebviewjavascriptbridge (callback) {if(window. Webviewjavascriptbridge) {callback (Webviewjavascriptbridge)}Else{Document.addeventlistener (' Webviewjavascriptbridgeready ', function () {callback (Webviewjavascriptbridge)},false)}}connectwebviewjavascriptbridge (function (bridge) {/*Init your app here*/Bridge.init (function (message, responsecallback) {alert (' Received message: ' +message)if(responsecallback) {Responsecallback ("Right Back Atcha")}}) Bridge.send (' Hello from the JavaScript ') Bridge.send (' Respond to this ', Function Responsecallback (responsedata) {Console.log ("Javascript got its response", ResponseData)})})
Contributors & Forks
Contributors:https://github.com/marcuswestin/webviewjavascriptbridge/graphs/contributors
Forks:https://github.com/marcuswestin/webviewjavascriptbridge/network/members
API Reference
OBJC API
[Webviewjavascriptbridge Bridgeforwebview: (uiwebview/webview*) WebView handler: (Wvjbhandler) handler]
[Webviewjavascriptbridge Bridgeforwebview:
(uiwebview/webview*) WebView webviewdelegate:
(uiwebviewdelegate*) Webviewdelegate handler: (Wvjbhandler) handler]
Create a JavaScript bridge for Web view.
If JavaScript needs a feedback, then wvjbresponsecallback cannot be nil.
Of course, through Webviewdelegate: (uiwebviewdelegate*) Webviewdelegate You can get Web view life cycle events.
Example:
[Webviewjavascriptbridge bridgeforwebview:webview handler:^(id data, Wvjbresponsecallback responseCallback) { NSLog (@"Received message from JavaScript:%@", data); if (responsecallback) {responsecallback (@"right back Atcha");}] [Webviewjavascriptbridge Bridgeforwebview:webview webviewdelegate:self Handler: /* */ }];
[Bridge Send: (ID) data]
[Bridge Send: (ID) Data responsecallback: (wvjbresponsecallback) Responsecallback]
Send a message to JavaScript. And after the message is successfully sent, it can be responsecallback block to make some response.
Example:
[Self.bridge send:@ "Hi"]; [Self.bridge send:[nsdictionary dictionarywithobject:@"Foo" forkey:@ "Bar"]; [Self.bridge send:@"I expect a response!" responsecallback:^(id responsedata) {NSLog (@"Got response!%@" c3>, ResponseData);}];
[Bridge Registerhandler: (nsstring*) HandlerName handler: (Wvjbhandler) handler]
Register a handler called HandlerName. JavaScript can be Webviewjavascriptbridge.callhandler ("HandlerName") to tune up this handler.
Example:
[Self.bridge registerhandler:@ "Getscreenheight" handler:^(ID data, Wvjbresponsecallback responsecallback) { Responsecallback ([NSNumber numberwithint:[uiscreen mainscreen].bounds.size.height]);}];
[Bridge Callhandler: (nsstring*) handlerName data: (ID) data]
[Bridge Callhandler: (nsstring*) handlerName data: (ID) Data responsecallback: (Wvjbresponsecallback) callback]
Tune up JavaScript called HandlerName's handler. After a successful call to handler, you can respond by Responsecallback block.
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);}];
Defining bundles
Webviewjavascriptbridge requires the WebViewJavascriptBridge.js.txt file to be embedded in the Web view to create a bridge over JS. The standard implementation is to use the Mainbundle Find this file. If you create a static library and you put the file somewhere else, you can find the WebViewJavascriptBridge.js.txt file using the following method:
[Webviewjavascriptbridge Bridgeforwebview:
(uiwebview/webview*) WebView webviewdelegate:
(uiwebviewdelegate*) Webviewdelegate handler: (Wvjbhandler) handler
ResourceBundle: (nsbundle*) bundle
Example:
[Webviewjavascriptbridge bridgeforwebview:_webview webviewdelegate:self handler:^(id data, Wvjbresponsecallback responsecallback) {NSLog (@"Received message from JavaScript:%@", data); } Resourcebundle:[nsbundle bundlewithurl:[[nsbundle Mainbundle] urlforresource:@"Resourcesbundle" withExtension : @ "bundle"]];
Javascript API
Document.addeventlistener (' Webviewjavascriptbridgeready ',
function Onbridgeready (event) {...}, false)
Waits for the Webviewjavascriptbridgeready DOM event.
Example:
function (event) {var bridge = Event.bridge// Start using the bridgefalse )
Ridge.init (function MessageHandler (data, response) {...})
Initialize the bridge. This will turn up the ' Webviewjavascriptbridgeready ' event handler.
This messagehandler function will receive [Bridge Send: (ID) data] and [Bridge send: (ID) data responsecallback via OBJC: (Wvjbresponsecallback) Responsecallback] method to send all messages.
If OBJC sends a message with Wvjbresponsecallback block, the message can be sent through the response object.
Example:
Bridge.init (function(data, Responsecallback) {alert ("Got data" + json.stringify (data)) if (responsecallback) {responsecallback ("right Back atcha!" )}})
Bridge.send ("Hi there!")
Bridge.send ({Foo: "Bar"})
Bridge.send (data, function Responsecallback (responsedata) {...
})
Send a message to OBJC. The Responsecallback function can be used to respond to a successful delivery.
Example:
Bridge.send ("Hi there!" ) bridge.send (function(responsedata) {alert ("I got a response! "+Json.stringify (responsedata))})
Bridge.registerhandler ("HandlerName", function (ResponseData) {...})
Register a handler called HandlerName. OBJC can pass [bridge Callhandler: "HandlerName" data:@ "foo"] and [Bridge Callhandler: "HandlerName" data:@ "foo" responsecallback:^ (id responsedata) {...}] Two ways to tune up this handler.
Example:
function (data) {alert (data)}) Bridge.registerhandler (function(data, Responsecallback) { Responsecallback (Document.location.toString ())})
IOS4 support (including Jsonkit)
Note: iOS4 support has not been tested in V2 +.
Webviewjavascriptbridge uses nsjsonserialization by default. If you need iOS 4 support, you can use Jsonkit and add Use_jsonkit preprocessing macros to your project.
Webviewjavascriptbridge-obj-c and JavaScript Bridging the message