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,内嵌到手机上,这对我来说完全是一个陌生的领域,不过也正好给自己一个机会来学习,最近做到要跟服务器交互这部分,这部分可是卡了 ...
随机推荐
- Flask项目之手机端租房网站的实战开发(四)
说明:该篇博客是博主一字一码编写的,实属不易,请尊重原创,谢谢大家! 接着上一篇博客继续往下写 :https://blog.csdn.net/qq_41782425/article/details/8 ...
- Python 极简教程(九)元组 tuple
元组(tuple)是 Python 中的一种序列.和列表类似,但是元组不可变. 也就是说元组一旦声明后,值就不能再改变.我们先来看看元组的样式: >>> t = () # 空元组 & ...
- PythonNET网络编程3
IO IO input output 在内存中存在数据交换的操作都可以认为是IO操作 和终端交互 : input print 和磁盘交互 : read write 和网络交互 : recv send ...
- VC 常见问题百问
http://www.cnblogs.com/cy163/archive/2006/06/19/429796.html 经典Vc书 Charles Petzold 的<Programming W ...
- android Email总结文档
目录:src\com.android.email.activity 一. Welcome.java 根据AndroidManifest.xml可知该文件为程序入口文件: 加载该文件时,查询数据库账户列 ...
- iOS_06_基本运算符
一.算术运算 c语言一共有34种运算符,包括了常见的加减乘除 1.加法运算+ # 除了能做加法运算,还能表示正号:+5.+90 2.减法运算- # 除了能做减法运算,还能表示符号:-10.-200 3 ...
- FragmentPagerAdapter和FragmentStatePagerAdapter的差别
ViewPager同意用户通过左右滑动显示不同页面的数据.而这些页面须要PagerAdapter管理. 经常使用的有FragmentPagerAdapter和FragmentStatePagerAda ...
- 解题报告 之 HDU5305 Friends
解题报告 之 HDU5305 Friends Description There are people and pairs of friends. For every pair of friend ...
- js课程 2-8 js内置对象有哪些
js课程 2-8 js内置对象有哪些 一.总结 一句话总结:JS中内置了17个对象,常用的是Array对象.Date对象.正则表达式对象.string对象.Global对象. 1.js常用对象有哪些? ...
- ORACEL上传BLOB,深度遍历文件夹
// uploadingDlg.cpp : 实现文件// #include "stdafx.h"#include "uploading.h"#include & ...