android或ios:app与html5通信解决方案
下面只是前端示例代码,后端代码请参考:
- git https://github.com/marcuswestin/WebViewJavascriptBridge
- ios http://www.jianshu.com/p/feec40aff59a?utm_campaign=hugo&utm_medium=reader_share&utm_content=note
- android http://www.jianshu.com/p/b3d120753bbb
<html> <head> <meta content="text/html; charset=utf-8" http-equiv="content-type"> <title> js调用java </title> </head> <body> <p> <xmp id="show"> </xmp> </p> <p> <xmp id="init"> </xmp> </p> <p> <input type="text" id="text1" value="用户名(username)" /> </p> <p> <input type="text" id="text2" value="password" /> </p> <p> <input type="button" id="enter" value="发消息给Native" onclick="testClick();" /> </p> <p> <input type="button" id="enter1" value="调用Native方法" onclick="testClick1();" /> </p> <p> <input type="button" id="enter2" value="显示html" onclick="testDiv();" /> </p> <p> <input type="file" value="打开文件" /> </p> </body> <script> function testDiv() { document.getElementById("show").innerHTML = document.getElementsByTagName("html")[0].innerHTML; } function testClick() { var str1 = document.getElementById("text1").value; var str2 = document.getElementById("text2").value; //send message to native var data = {id: 1, content: "这是一个图片 <img src="a.png"/> test hahaha"}; window.WebViewJavascriptBridge.send( data , function(responseData) { document.getElementById("show").innerHTML = "repsonseData from java, data = " + responseData } ); } function testClick1() { var str1 = document.getElementById("text1").value; var str2 = document.getElementById("text2").value; //call native method window.WebViewJavascriptBridge.callHandler( 'submitFromWeb' , {'param': '中文测试'} , function(responseData) { document.getElementById("show").innerHTML = "send get responseData from java, data = " + responseData } ); } function bridgeLog(logContent) { document.getElementById("show").innerHTML = logContent; } function connectWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { callback(WebViewJavascriptBridge) } else { document.addEventListener( 'WebViewJavascriptBridgeReady' , function() { callback(WebViewJavascriptBridge) }, false ); } } connectWebViewJavascriptBridge(function(bridge) { bridge.init(function(message, responseCallback) { console.log('JS got a message', message); var data = { 'Javascript Responds': '测试中文!' }; console.log('JS responding with', data); responseCallback(data); }); bridge.registerHandler("functionInJs", function(data, responseCallback) { document.getElementById("show").innerHTML = ("data from Java: = " + data); var responseData = "Javascript Says Right back aka!"; responseCallback(responseData); }); }) </script> </html>