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的更多相关文章

  1. iOS与HTML5交互方法总结(转)

    今天小编在找技术文章的时候,发现这样一个标题:iOS与HTML5交互方法总结,怎么看着这么熟悉呢?   还以为是刚哥用了别的文章,点进去一看,原来是刚哥自己写的文章,他们转载的,而且还上了Dev St ...

  2. iOS与HTML5交互方法总结(修正)

    摘要 看了不少别人写的博客或者论坛,关于iOS与HTML5交互方法大概主要有5种方式: 1. 利用WKWebView进行交互(系统API) 2. 利用UIWebView进行交互(系统API) 3. 苹 ...

  3. UIWebView中JS与OC交互 WebViewJavascriptBridge的使用

    一.综述 现在很多的应用都会在多种平台上发布,所以很多程序猿们都开始使用Hybrid App的设计模式.就是在app上嵌入网页,只要写一份网页代码,就可以跑在不同的系统上.在iOS中,app多是通过W ...

  4. iOS中JS 与OC的交互(JavaScriptCore.framework)

    iOS中实现js与oc的交互,目前网上也有不少流行的开源解决方案: 如:react native 当然一些轻量级的任务使用系统提供的UIWebView 以及JavaScriptCore.framewo ...

  5. iOS中使用UIWebView与JS进行交互

    iOS中使用UIWebView与JS进行交互 前一段忙着面试和复习,这两天终于考完试了,下学期的实习也有了着落,把最近学的东西更新一下,首先是使用UIWebView与JS进行交互 在webView中我 ...

  6. iOS中UIWebView使用JS交互 - 机智的新手

    iOS中偶尔也会用到webview来显示一些内容,比如新闻,或者一段介绍.但是用的不多,现在来教大家怎么使用js跟webview进行交互. 这里就拿点击图片获取图片路径为例: 1.测试页面html & ...

  7. iOS中js与objective-c的交互(转)

    因为在iOS中没有WebKit.Framework这个库的,所以也就没有 windowScriptObject对象方法了.要是有这个的方法的话 就方便多了,(ps:MacOS中有貌似) 现在我们利用其 ...

  8. iOS中UIWebView使用JS交互

    iOS中偶尔也会用到webview来显示一些内容,比如新闻,或者一段介绍.但是用的不多,现在来教大家怎么使用js跟webview进行交互. 这里就拿点击图片获取图片路径为例: 1.测试页面html & ...

  9. 在Html5中与服务器交互

    转自原文 在Html5中与服务器交互 刚刚涉足职场,上头就要我研究HTML5,内嵌到手机上,这对我来说完全是一个陌生的领域,不过也正好给自己一个机会来学习,最近做到要跟服务器交互这部分,这部分可是卡了 ...

随机推荐

  1. 100.dll调用

    在dll中声明 _declspec(dllexport) ; _declspec(dllexport)void go() { MessageBoxA(, ); } 调用dll HINSTANCE hl ...

  2. loadrunner11 +Win7 + 支持ie9,录制成功

    loadrunner11 支持ie9,录制成功 中文例子: https://wenku.baidu.com/view/1123925377232f60ddcca149.html http://blog ...

  3. Mongodb总结2-Java版本的HelloWorld-CRUD例子

    2013年,写的CRUD太简单了,今天在原来的基础上,稍微完善了下,用了更多语法,比如排序sort.in语句等. 参考了<Mongodb权威指南-第1版-高清>,等下上传到CSDN下载频道 ...

  4. MyCat中间件:读写分离(转)

    利用MyCat中间件实现读写分离 需要两步: 1.搭建MySQL主从复制环境 2.配置MyCat读写分离策略 一.搭建MySQL主从环境 参考上一篇博文:MySQL系列之七:主从复制 二.配置MyCa ...

  5. 关于python的深浅拷贝、赋值

    https://blog.csdn.net/weixin_39750084/article/details/81435454

  6. 硬件——STM32 , 软件框架

    单片机应用程序的框架大概有三种: 1,简单的前后台顺序执行程序. 2,时间片轮询法. 3,应用操作系统. 下面我们主要来讲解时间片轮询法: 在这里我们先介绍一下定时器的复用功能.就是使用1个定时器,可 ...

  7. var let 区别

    var a = 5; var b = 10; if (a === 5) { let a = 4; // if 块级作用域 var b = 1; // 函数级作用域 console.log(a); // ...

  8. Day1:变量

    一.变量用来干嘛的 用来存东西的,方便后面调用 二.如何定义变量 name = "Hiuhung Wan" 变量名 = 值,一个等号是赋值号,右边的值赋值给左边 三.变量的一些用法 ...

  9. HttpWatch--time chart分析

    这是一个IE的插件,下载可以点这里.下载后解压如下图所示,一共有4个文件.HttpWatch Professional是单独软件,可以单独使用. 解压后有四个文件 插件安装时,只需运行httpwatc ...

  10. hunnu 11545小明的烦恼——找路径 (最大流)

    小明的烦恼--找路径  Time Limit: 2000ms, Special Time Limit:5000ms, Memory Limit:32768KB Total submit users: ...