<!doctype html>
<html><head>
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type='text/css'>
html { font-family:Helvetica; color:#222; }
h1 { color:steelblue; font-size:24px; margin-top:24px; }
button { margin:0 3px 10px; font-size:12px; }
.logLine { border-bottom:1px solid #ccc; padding:4px 2px; font-family:courier; font-size:11px; }
</style>
</head><body>
<h1>WebViewJavascriptBridge Demo</h1>
<div id="buttons"></div>
<div id="log"></div>
<button id="button-ios">(JS调OC方法) testObjcCallback</button>
<script>
window.onerror = function(err) {
log('window.onerror: ' + err)
};
//给WebViewJavascriptBridgeReady事件注册一个Listener
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener('WebViewJavascriptBridgeReady', function() {
callback(WebViewJavascriptBridge)
}, false)
}
}
connectWebViewJavascriptBridge(function(bridge) {
var uniqueId = 1;
function log(message, data) {//日志记录
var log = document.getElementById('log');
var el = document.createElement('div');
el.className = 'logLine';
el.innerHTML = uniqueId++ + '. ' + message + ':<br/>' + JSON.stringify(data);
if (log.children.length) { log.insertBefore(el, log.children[0]) }
else { log.appendChild(el) }
}
//初始化操作,并定义默认的消息处理逻辑
bridge.init(function(message, responseCallback) {
var data = { 'Javascript Responds':'Wee!' };
responseCallback(data)
});
//注册一个名为testJavascriptHandler的处理器,并定义用于响应的处理逻辑
bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
var responseData = { 'Javascript Says':'Right back atcha!' };
responseCallback(responseData)
});
//创建一个发送消息给native端的按钮
var button = document.getElementById('buttons').appendChild(document.createElement('button'))
button.innerHTML = '发送消息给native端';
button.onclick = function(e) {
e.preventDefault();
var data = '你好native端,消息来自JS端按钮';
log('开始发送', data);
bridge.send(data, function(responseData) {
log('发送完成', responseData)
})
};
document.body.appendChild(document.createElement('br'));
//var callbackButton = document.getElementById('buttons').appendChild(document.createElement('button'));
//callbackButton.innerHTML = '(JS调OC方法) testObjcCallback';
var callbackButton = document.getElementById('button-ios');
callbackButton.onclick = function(e) {
e.preventDefault();
log('执行回调');
//调用名为testObjcCallback的native端处理器,并传递参数,同时设置回调处理逻辑
bridge.callHandler('testObjcCallback', {'name': 'congcocng'}, function(response) {
log('回调完成', response)
})
}
})
</script>
</body>
</html>
WebViewJavascriptBridge Demo (js与native之间的数据互动)
最新推荐文章于 2024-08-16 09:00:37 发布