Skip to content

Instantly share code, notes, and snippets.

@5ZSQ
Created June 7, 2017 10:01
Show Gist options
  • Save 5ZSQ/cb7392b42fd45d546a6732fd2076a4de to your computer and use it in GitHub Desktop.
Save 5ZSQ/cb7392b42fd45d546a6732fd2076a4de to your computer and use it in GitHub Desktop.
iOS - webview [Objectc-js]通信
>使用 `WebViewJavascriptBridge`库
/*这段代码是固定的,必须要放到js中*/
function setupWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
/*与OC交互的所有JS方法都要放在此处注册,才能调用通过JS调用OC或者让OC调用这里的JS*/
setupWebViewJavascriptBridge(function(bridge) {
var phone = document.getElementById("mc_phone").value;
var verify_code = document.getElementById("mc_verify_code").value;
var password = document.getElementById("mc_new_password").value;
bridge.callHandler("thirdLoginSuccess",{'phone':phone, 'verify_code':verify_code, 'password':password});
});
------------------------------
/* Initialize your app here */
/*我们在这注册一个js调用OC的方法,不带参数,且不用ObjC端反馈结果给JS:打开本demo对应的博文*/
bridge.registerHandler('openWebviewBridgeArticle', function() {
log("openWebviewBridgeArticle was called with by ObjC")
})
/*JS给ObjC提供公开的API,在ObjC端可以手动调用JS的这个API。接收ObjC传过来的参数,且可以回调ObjC*/
bridge.registerHandler('getUserInfos', function(data, responseCallback) {
log("Get user information from ObjC: ", data)
responseCallback({'userId': '123456', 'blog': '标哥的技术博客'})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment