iOS中html5的交互:WebViewJavascriptBridge
https://github.com/marcuswestin/WebViewJavascriptBridge
Setup & Examples (iOS & OSX)
Start with 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:
1) 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"
2) Import the header file and declare an ivar property:
#import "WebViewJavascriptBridge.h"
...
@property WebViewJavascriptBridge* bridge;
3) Instantiate WebViewJavascriptBridge with a UIWebView (iOS) or WebView (OSX):
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"Received message from javascript: %@", data);
responseCallback(@"Right back atcha");
}];
4) Go ahead and 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, will you?" responseCallback:^(id responseData) {
NSLog(@"ObjC got its response! %@", responseData);
}];
4) Finally, set up 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('Please respond to this', function responseCallback(responseData) {
console.log("Javascript got its response", responseData)
})
})
WKWebView Support (iOS 8 & OS 10.10)
WARNING: WKWebView still has many bugs and missing network APIs. It may not be a simple drop-in replacement.
WebViewJavascriptBridge supports WKWebView for iOS 8 and OSX Yosemite. In order to use WKWebView you need to instantiate the WKWebViewJavascriptBridge
. The rest of the WKWebViewJavascriptBridge
API is the same as WebViewJavascriptBridge
.
1) Import the header file:
#import "WKWebViewJavascriptBridge.h"
2) Instantiate WKWebViewJavascriptBridge and with a WKWebView object
WKWebViewJavascriptBridge* bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"Received message from javascript: %@", data);
responseCallback(@"Right back atcha");
}];
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 the given web view.
The WVJBResponseCallback
will not be nil
if the javascript expects a response.
Optionally, pass in webViewDelegate:(UIWebViewDelegate*)webViewDelegate
if you need to respond to the web view's lifecycle 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:^(id data, WVJBResponseCallback responseCallback) { /* ... */ }];
[bridge send:(id)data]
[bridge send:(id)data responseCallback:(WVJBResponseCallback)responseCallback]
Send a message to javascript. Optionally expect a response by giving a responseCallback
block.
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! %@", responseData);
}];
[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]);
}];
[bridge callHandler:(NSString*)handlerName data:(id)data]
[bridge callHandler:(NSString*)handlerName data:(id)data responseCallback:(WVJBResponseCallback)callback]
Call the javascript handler called handlerName
. Optionally expect a response by giving a 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);
}];
Custom bundle
WebViewJavascriptBridge
requires WebViewJavascriptBridge.js.txt
file that is injected into web view to create a bridge on JS side. Standard implementation uses mainBundle
to search for this file. If you e.g. build a static library and you have that file placed somewhere else you can use this method to specify which bundle should be searched for WebViewJavascriptBridge.js.txt
file:
[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)
Always wait for the WebViewJavascriptBridgeReady
DOM event.
Example:
document.addEventListener('WebViewJavascriptBridgeReady', function(event) {
var bridge = event.bridge
// Start using the bridge
}, false)
bridge.init(function messageHandler(data, response) { ... })
Initialize the bridge. This should be called inside of the 'WebViewJavascriptBridgeReady'
event handler.
The messageHandler
function will receive all messages sent from ObjC via [bridge send:(id)data]
and [bridge send:(id)data responseCallback:(WVJBResponseCallback)responseCallback]
.
The response
object will be defined if if ObjC sent the message with a WVJBResponseCallback
block.
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. Optionally expect a response by giving a responseCallback
function.
Example:
bridge.send("Hi there!")
bridge.send("Hi there!", function(responseData) {
alert("I got a response! "+JSON.stringify(responseData))
})
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())
})
iOS4 support (with JSONKit)
Note: iOS4 support has not yet been tested in v2+.
WebViewJavascriptBridge uses NSJSONSerialization
by default. If you need iOS 4 support then you can use JSONKit, and add USE_JSONKIT
to the preprocessor macros for your project.
iOS中html5的交互:WebViewJavascriptBridge的更多相关文章
- iOS与HTML5交互方法总结(转)
今天小编在找技术文章的时候,发现这样一个标题:iOS与HTML5交互方法总结,怎么看着这么熟悉呢? 还以为是刚哥用了别的文章,点进去一看,原来是刚哥自己写的文章,他们转载的,而且还上了Dev St ...
- iOS与HTML5交互方法总结(修正)
摘要 看了不少别人写的博客或者论坛,关于iOS与HTML5交互方法大概主要有5种方式: 1. 利用WKWebView进行交互(系统API) 2. 利用UIWebView进行交互(系统API) 3. 苹 ...
- UIWebView中JS与OC交互 WebViewJavascriptBridge的使用
一.综述 现在很多的应用都会在多种平台上发布,所以很多程序猿们都开始使用Hybrid App的设计模式.就是在app上嵌入网页,只要写一份网页代码,就可以跑在不同的系统上.在iOS中,app多是通过W ...
- iOS中JS 与OC的交互(JavaScriptCore.framework)
iOS中实现js与oc的交互,目前网上也有不少流行的开源解决方案: 如:react native 当然一些轻量级的任务使用系统提供的UIWebView 以及JavaScriptCore.framewo ...
- iOS中使用UIWebView与JS进行交互
iOS中使用UIWebView与JS进行交互 前一段忙着面试和复习,这两天终于考完试了,下学期的实习也有了着落,把最近学的东西更新一下,首先是使用UIWebView与JS进行交互 在webView中我 ...
- iOS中UIWebView使用JS交互 - 机智的新手
iOS中偶尔也会用到webview来显示一些内容,比如新闻,或者一段介绍.但是用的不多,现在来教大家怎么使用js跟webview进行交互. 这里就拿点击图片获取图片路径为例: 1.测试页面html & ...
- iOS中js与objective-c的交互(转)
因为在iOS中没有WebKit.Framework这个库的,所以也就没有 windowScriptObject对象方法了.要是有这个的方法的话 就方便多了,(ps:MacOS中有貌似) 现在我们利用其 ...
- iOS中UIWebView使用JS交互
iOS中偶尔也会用到webview来显示一些内容,比如新闻,或者一段介绍.但是用的不多,现在来教大家怎么使用js跟webview进行交互. 这里就拿点击图片获取图片路径为例: 1.测试页面html & ...
- 在Html5中与服务器交互
转自原文 在Html5中与服务器交互 刚刚涉足职场,上头就要我研究HTML5,内嵌到手机上,这对我来说完全是一个陌生的领域,不过也正好给自己一个机会来学习,最近做到要跟服务器交互这部分,这部分可是卡了 ...
随机推荐
- POJ Oulipo(KMP模板题)
题意:找出模板在文本串中出现的次数 思路:KMP模板题 #include<cstdio> #include<cstring> #include<cmath> #in ...
- python基础--数值类型和序列类型
Python中数值类型:int(整数),float(浮点数),True/False(布尔值,首字母必须大写) int:1 #任意整数 float:2.3 #小数 python赋值: a = ...
- 使用Docker来运行WebApp
原文:使用Docker来运行WebApp (作者:陈玓玏) 1.加载镜像到容器并运行webapp脚本 先进入管理员模式: su root 然后使用已有的webapp镜像来练习在docker上运行web ...
- Mongodb总结6-数据库启动、停止、备份等命令
#启动Mongodb默认启动,需要在/data/db,Windows下对应的目录是Mongod.exe所在磁盘分区的根目录,例如Mongodb存放在D:/Mongodb,那么对应的路径就是D:/dat ...
- Invalid property 'annotatedClasses' of bean class
Invalid property 'annotatedClasses' of bean class 在整合Hibernate和Spring时出现,Invalid property 'annotated ...
- amazeui学习笔记--css(布局相关1)--网格Grid
amazeui学习笔记--css(布局相关1)--网格Grid 一.总结 基本使用 1.div+class布局:amaze里面采取的就是div+class的布局方式 <div class=&q ...
- TCP超时重传机制
TCP协议在能够发送数据之前就建立起了"连接".要实现这个连接,启动TCP连接的那一方首先将发送一个SYN数据包.这只是一个不包含数据的数据包, 然后,打开SYN标记.如果另一方同 ...
- AndroidActivity跳转动画,让你的APP瞬间绚丽起来
我们都知道绚丽的APP总会给用户耳目一新的感觉,为了抓住用户更大网络公司使出浑身解数让自己的产品更绚丽,而绚丽最简单的效果就是Activity跳转效果,不仅能够让用户看起来舒服,并且实现起来也特别简单 ...
- uvalive 6393(uva 1572) Self-Assembly 拓扑排序
题意: 给出一些正方形,这些正方形的每一条边都有一个标号.这些标号有两种形式:1.一个大写字母+一个加减号(如:A+, B-, A-......), 2.两个0(如:00):这些正方形能够任意翻转和旋 ...
- iOS之StatusBar详解
随便打开手机上的主流APP,我们不难发现它们的状态栏都是跟导航栏保持一致的背景颜色,如下图的微信和instagram: WECHAT.PNG INS.PNG 那么今天我们就来说一下StatusBar这 ...