This article for you to introduce a good people to develop open source small project: Webviewjavascriptbridge.
Download Webviewjavascriptbridge Address
It elegantly implements the intermodulation between JS and iOS objective-c Nativecode when using UIWebView, supports message sending, receiving, registering and invoking the Message processor, and setting callback for message processing.
Just like the name of the project, it is the bridge that connects UIWebView and JavaScript. After joining the project, their interaction with each other became very friendly.
When interacting with JS in the UIWebView in native code, like this:
Sends a message to the UI side and defines the callback processing logic
[_bridge send:@ "A string sent from OBJC before Webview have loaded." Responsecallback:^ (ID error, ID responsedata) {
if (Error) {NSLog (@ "Uh Oh-i got an error:%@", error);}
NSLog (@ "OBJC got response!%@%@", error, ResponseData);
}];
The UIWebView in the JS and native code interaction also becomes very concise, such as when the processor is called, you can define the callback processing logic:
Call the native-side processor named Testobjccallback and pass the parameters while setting the callback processing logic
Bridge.callhandler (' Testobjccallback ', {' foo ': ' Bar '}, function (response) {
<span style= "White-space:pre" > </span>log (' Got response from Testobjccallback ', response)
})
Let's take a look at its implementation, which contains three files in total:
WebViewJavascriptBridge.h
Webviewjavascriptbridge.m
WebViewJavascriptBridge.js.txt
They interact in the following modes:
Obviously: WebViewJavascriptBridge.js.txt is mainly used to connect Web page in UIWebView, and webviewjavascriptbridge.h/ M is mainly used to deal with OBJC's nativecode. They as a whole, actually played a "bridge" role, these three files encapsulate their specific interactive processing, only open out some of the external business processing API, so you need to UIWebView and nativecode interaction, when you introduce the library, There is no need to consider too many interaction issues. The whole bridge is transparent to you, and when you feel programmed, it's as clear as the front end and back end of Web programming.
Simply list what features it can achieve:
For the sake of expression, I call it the UI side for UIWebView, and the processing code of OBJC is called the native end.
"1" UI side
(1) The UI side supports setting the default processor for the message at initialization (the message here refers to the message received from the native side)
(2) Sending messages from the UI side to the native side and supporting the definition of callback processing after the native-side response
(3) The UI side invokes the processor defined by the native and supports the callback processing definition after the native-side response
(4) UI-Side registration processor (for native-side invocation), and support for definition of native-side response processing logic
"2" native end
(1) The native side supports the default processor for setting messages at initialization (the message here refers to messages sent from the UI side)
(2) Send messages from the native end to the UI side and support the definition of callback processing logic after the UI-side response
(3) The native end invokes the processor defined by the UI side and supports the definition of the callback processing logic on the native side after the UI-side gives the response
(4) The native-side registers the processor (for UI-side invocation), and supports the UI-side of the definition UI for response processing logic and the native-side is completely peer-on, and the implementation is also equivalent. One section is the sender of the message, and the other is the receiving end. To cause confusion here, I need to explain the definition of "response" and "callback" that I use here in this context:
(1) Response: The receiving end gives the sender the answer
(2) Callback: processing logic that is invoked at the receiving end after the sender receives a response from the receiving end
Below to analyze the source code:
WebViewJavascriptBridge.js.txt:
The main tasks are as follows:
(1) creates an IFRAME for sending a message (by creating a hidden ifrmae and setting its URL to make a request that triggers the UIWebView shouldstartloadwithrequest callback protocol)
(2) A core object Webviewjavascriptbridge is created and several methods are defined for it, mostly public API methods
(3) An event was created: Webviewjavascriptbridgeready, and dispatch (triggered) it.
Code interpretation
UI-Side implementation
for (1), the corresponding code is as follows:
/*
* Create an IFRAME, set hide and add to Dom
*/
function _createqueuereadyiframe (DOC) {
Messagingiframe = doc.createelement (' iframe ')
MessagingIframe.style.display = ' None '
Doc.documentElement.appendChild (Messagingiframe)
}
For Webviewjavascriptbridge in (2), the object has the following methods:
Window. Webviewjavascriptbridge = {
Init:init,
Send:send,
Registerhandler:registerhandler,
Callhandler:callhandler,
_fetchqueue: _fetchqueue,
_HANDLEMESSAGEFROMOBJC: _HANDLEMESSAGEFROMOBJC
}
Implementation of the method:
<span style= "White-space:pre" > </span>/*
* Initialize method, inject the default message processor
* The default message processor is used when processing messages from OBJC, if the message is not set by the processor, the default processor is processed
*/
function init (messagehandler) {
if (Webviewjavascriptbridge._messagehandler) {throw new Error (' webviewjavascriptbridge.init called Twice ')}
Webviewjavascriptbridge._messagehandler = MessageHandler
var receivedmessages = Receivemessagequeue
Receivemessagequeue = null
If the receive queue has a message, the processing
for (var i=0; i<receivedmessages.length; i++) {
_DISPATCHMESSAGEFROMOBJC (Receivedmessages[i])
}
}
<span style= "White-space:pre" > </span>/*
* Send message and set callback
*/
function send (data, responsecallback) {
_dosend ({data:data}, Responsecallback)
}
/*
* Register Message Processor
*/
function Registerhandler (handlerName, handler) {
Messagehandlers[handlername] = Handler
}
/*
* Call the processor and set the callback
*/
function Callhandler (handlerName, data, Responsecallback) {
_dosend ({data:data, handlername:handlername}, Responsecallback)
}
The two internal methods involved:
<span style= "White-space:pre" > </span>/*
* Internal method: Sending of messages
*/
function _dosend (message, Responsecallback) {
If a callback is defined
if (responsecallback) {
To create a unique identity for a callback object
var callbackid = ' js_cb_ ' + (uniqueid++)
and stored in a collection object.
Responsecallbacks[callbackid] = Responsecallback
Added a Key-value pair-' callbackid ': callbackid
message[' callbackid '] = Callbackid
}
Sendmessagequeue.push (json.stringify (message))
MESSAGINGIFRAME.SRC = Custom_protocol_scheme + '://' + Queue_has_message
}
<span style= "White-space:pre" > </span>/*
* Internal method: Handling messages from OBJC
*/
function _DISPATCHMESSAGEFROMOBJC (Messagejson) {
SetTimeout (function _timeoutdispatchmessagefromobjc () {
var message = Json.parse (Messagejson)
var MessageHandler
if (Message.responseid) {
Remove the callback function object and execute
var responsecallback = Responsecallbacks[message.responseid]
Responsecallback (Message.error, Message.responsedata)
Delete Responsecallbacks[message.responseid]
} else {
var response
if (Message.callbackid) {
var Callbackresponseid = Message.callbackid
Response = {
Respondwith:function (responsedata) {
_dosend ({responseid:callbackresponseid, responsedata:responsedata})
},
Respondwitherror:function (Error) {
_dosend ({responseid:callbackresponseid, error:error})
}
}
}
var handler = Webviewjavascriptbridge._messagehandler
If the message contains a message processor, the processor is used, otherwise the default processor is used
if (message.handlername) {
Handler = Messagehandlers[message.handlername]
}
try {
Handler (Message.data, Response)
} catch (Exception) {
Console.log ("WebViewJavascriptBridge:WARNING:javascript handler threw.", message, exception)
}
}
})
}
There are also two JS methods that are intended to be called directly by the native side (they are also services for the native end):
<span style= "White-space:pre" > </span>/*
* Gets the queue, separating each element in the queue with a delimiter and then connecting it to a string called "Native-side"
*/
function _fetchqueue () {
var messagequeuestring = Sendmessagequeue.join (message_separator)
Sendmessagequeue = []
Return messagequeuestring
}
<span style= "White-space:pre" > </span>/*
* Processing of messages from OBJC "native-side call"
*/
function _HANDLEMESSAGEFROMOBJC (Messagejson) {
If the receive queue object exists, the message is queued or processed directly
if (receivemessagequeue) {
Receivemessagequeue.push (Messagejson)
} else {
_DISPATCHMESSAGEFROMOBJC (Messagejson)
}
}
The last piece of code is to define an event and trigger it, and set the Webviewjavascriptbridge object defined above as a property of the event:
<span style= "White-space:pre" > </span>var doc = document
_createqueuereadyiframe (DOC)
Create and instantiate an event object
var readyevent = doc.createevent (' Events ')
Readyevent.initevent (' Webviewjavascriptbridgeready ')
Readyevent.bridge = Webviewjavascriptbridge
Triggering events
Doc.dispatchevent (readyevent)
Native End Implementation
In fact, basically similar to the above, just because the syntax is different (so I said the two ends are equivalent): WEBVIEWJAVASCRIPTBRIDGE.H/.M
It can actually be seen as a UIWebView controller that implements the Uiwebviewdelegate protocol:
@interface Webviewjavascriptbridge:nsobject <UIWebViewDelegate>
+ (ID) Bridgeforwebview: (uiwebview*) WebView handler: (Wvjbhandler) handler;
+ (ID) Bridgeforwebview: (uiwebview*) WebView webviewdelegate: (ID <UIWebViewDelegate>) webviewdelegate handler: ( Wvjbhandler) handler;
+ (void) enableLogging;
-(void) Send: (ID) message;
-(void) Send: (ID) message responsecallback: (wvjbresponsecallback) Responsecallback;
-(void) Registerhandler: (nsstring*) HandlerName handler: (Wvjbhandler) handler;
-(void) Callhandler: (nsstring*) HandlerName;
-(void) Callhandler: (nsstring*) handlerName data: (ID) data;
-(void) Callhandler: (nsstring*) handlerName data: (ID) Data responsecallback: (wvjbresponsecallback) Responsecallback;
@end
The implementation of the method is actually similar to the previous one, here we only look at a UIWebView protocol method: Shouldstartloadwithrequest:
-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype {
if (WebView! = _webview) {return YES;}
Nsurl *url = [request URL];
if ([[URL scheme] Isequaltostring:custom_protocol_scheme]) {
There is data in the queue
if ([[[URL Host] isequaltostring:queue_has_message]) {
Brush out the data in the queue
[Self _flushmessagequeue];
} else {
NSLog (@ "WebViewJavascriptBridge:WARNING:Received unknown webviewjavascriptbridge command%@://%@", Custom_protocol_ SCHEME, [url path]);
}
return NO;
} else if (self.webviewdelegate) {
return [self.webviewdelegate Webview:webview shouldstartloadwithrequest:request Navigationtype:navigationtype];
} else {
return YES;
}
}
Using the example
UI Side
<span style= "White-space:pre" > </span>//to webviewjavascriptbridgeready event Register a listener
Document.addeventlistener (' Webviewjavascriptbridgeready ', Onbridgeready, False)
<span style= "White-space:pre" > </span>//Event Response Processing
function Onbridgeready (event) {
var bridge = Event.bridge
var uniqueId = 1
<span style= "White-space:pre" > </span>//logging
function log (message, data) {
var log = document.getElementById (' log ')
var el = document.createelement (' div ')
El.classname = ' Logline '
el.innerhtml = uniqueid++ + '. ' + message + (data? ': ' + json.stringify (data): ')
if (log.children.length) {Log.insertbefore (El, log.children[0])}
else {log.appendchild (EL)}
}
<span style= "White-space:pre" > </span>//initialization, and defines the default message processing logic
Bridge.init (function (message) {
Log (' JS got a message ', message)
})
<span style= "White-space:pre" > </span>//register a processor named Testjavascripthandler and define the processing logic for the response
Bridge.registerhandler (' Testjavascripthandler ', function (data, response) {
Log (' JS handler Testjavascripthandler was called ', data)
Response.respondwith ({' Javascript Says ': ' Right Back atcha! '})
})
<span style= "White-space:pre" > </span>//Create a button to send a message to the native side
var button = document.getElementById (' buttons '). AppendChild (document.createelement (' button '))
button.innerhtml = ' Send message to OBJC '
Button.ontouchstart = function (e) {
E.preventdefault ()
<span style= "White-space:pre" > </span>//Send Message
Bridge.send (' Hello from JS button ')
}
Document.body.appendChild (document.createelement (' BR '))
<span style= "White-space:pre" > </span>//Create a button to invoke the native-side processor
var Callbackbutton = document.getElementById (' buttons '). AppendChild (document.createelement (' button '))
callbackbutton.innerhtml = ' Fire Testobjccallback '
Callbackbutton.ontouchstart = function (e) {
E.preventdefault ()
Log ("calling handler Testobjccallback")
Call the native-side processor named Testobjccallback and pass the parameters while setting the callback processing logic
Bridge.callhandler (' Testobjccallback ', {' foo ': ' Bar '}, function (response) {
Log (' Got response from Testobjccallback ', response)
})
}
}
Native End
Instantiate a webview and add it to the window
uiwebview* WebView = [[UIWebView alloc] initWithFrame:self.window.bounds];
[Self.window Addsubview:webview];
Enable logging
[Webviewjavascriptbridge enableLogging];
Instantiate the Webviewjavascriptbridge and define the default message processor on the native side
_bridge = [Webviewjavascriptbridge bridgeforwebview:webview handler:^ (id data, Wvjbresponse *response) {
NSLog (@ "OBJC received message from JS:%@", data);
Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "OBJC got message from Javascript:" Message:data Delegate:nil can celbuttontitle:@ "OK" otherbuttontitles:nil];
[Alert show];
}];
Registers a processor named Testobjccallback that is called by the UI side and defines the processing logic for the response
[_bridge registerhandler:@ "Testobjccallback" handler:^ (ID data, wvjbresponse *response) {
NSLog (@ "testobjccallback called:%@", data);
[Response respondwith:@ "response from Testobjccallback"];
}];
Sends a message to the UI side and defines the callback processing logic
[_bridge send:@ "A string sent from OBJC before Webview have loaded." Responsecallback:^ (ID error, ID responsedata) {
if (Error) {NSLog (@ "Uh Oh-i got an error:%@", error);}
NSLog (@ "OBJC got response!%@%@", error, ResponseData);
}];
Invokes a processor named Testjavascripthandler defined on the UI side, with no callback defined
[_bridge callhandler:@ "Testjavascripthandler" Data:[nsdictionary dictionarywithobject:@ "before Ready" forKey:@ "foo" ]];
[Self renderbuttons:webview];
[Self loadexamplepage:webview];
Simply send a message to the UI side
[_bridge send:@ "A string sent from OBJC after Webview have loaded."];
Project run:
Things are very good hope that we support hehe!!!
Transferred from: http://www.lanrenios.com/tutorials/network/2012/1130/547.html
Webviewjavascriptbridge JS and iOS Native code intermodulation method