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. Writing Images to the Excel Sheet using PHPExcel--转载

    原文地址:http://www.walkswithme.net/writing-images-to-the-excel-sheet-using-phpexcel Writing images to t ...

  2. 无法解决 React 启动的报错

    E:\React\react_blank>npm start > react_blank@0.1.0 start E:\React\react_blank > react-scrip ...

  3. 【hdu 6000】Wash

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 因为每件衣服都是没有区别的. 只有洗衣机不同会影响洗衣时间. 那么我们把每台洗衣机洗衣的时间一开始都加入到队列中. 比如{2,3,6 ...

  4. amazeui学习笔记--css(常用组件7)--输入框组Input-group

    amazeui学习笔记--css(常用组件7)--输入框组Input-group 一.总结 1.使用:Input group 基于 Form 组件和 Button 组件扩展,依赖这两个组件.在容器上添 ...

  5. postman和fiddler的基本使用

    本文转自:https://www.cnblogs.com/qq909283/p/6826578.html 写在前面:本文主要的章节规划: 1.什么是接口测试 另外,有的时候会直接调用别的公司的接口,比 ...

  6. (素材源代码) 猫猫学IOS(五)UI之360等下载管理器九宫格UI

    猫猫分享,必须精品 先看效果 代码学习地址: 猫猫学IOS(五)UI之360等下载管理器九宫格UI 猫猫学IOS(五)UI之360等下载管理器九宫格UI http://blog.csdn.net/u0 ...

  7. 2、qq物联环境搭建

    1.使用easyopenjtag.openjtag来烧写uboot 2.体验uboot 插讲<网络设置_ping问题解决_远程登录ssh_文件互传ftp> 192.168.1.183 wi ...

  8. Surging -Demo部署

    原文:Surging -Demo部署 1.安装rabbitmq docker run -d --name rabbitmq --restart=unless-stopped --publish 567 ...

  9. 【Codeforces Round #440 (Div. 2) B】Maximum of Maximums of Minimums

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] k=1的时候就是最小值, k=2的时候,暴力枚举分割点. k=3的时候,最大值肯定能被"独立出来",则直接输出最 ...

  10. percona-toolkit源码编译安装

    安装依赖软件yum install perl-ExtUtils-CBuilder perl-ExtUtils-MakeMakeryum install  perl-Time-HiRes perl-DB ...