这次项目中有一个主页面完全是H5的页面,要求H5调用Native,js交互传值,看起来貌似很简单,网上教程一大堆,但是在实际开发过程中还是遇到很多问题,在这里记录一下。
- 首先,设置user agent,使前端可区分请求来自APP ,这里我设置的是"android_app/1.0.0",名称加版本号,具体设置什么大家可随意。
WebSettings settings = webView.getSettings();String ua = settings.getUserAgentString();settings.setUserAgentString(ua + "; android_app/1.0.0");
2.H5页面的登录,因为我们的应用不需要登录也能浏览,H5的页面有些也是不需要登陆的,所以点击H5页面需要登录的地方,要跳转到Native的页面登录,登录成功刷新H5页面,设置cookie,使WebView页面保持登录状态,具体代码如下:注:WebSettings的一些设置一定要放到设置cookie前面执行。设置cookie要注意作用域的问题,以及setCookie的时候最好分步设置,大家可以看下面的代码,我setCookie()了四次,不要把所有字符串拼接起来再一次setCookie,一次setCookie可能只会设置成功第一个分号前的cookie值。
public void synCookies(Context context, String host, String cookies) { try { CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); // 5.0以上版本的webview做了较大的改动,如:同步cookie的操作已经可以自动同步、但前提是我们必须开启第三方cookie的支持。 // cookieManager.setAcceptThirdPartyCookies(webView, true);//5.0以下的手机崩溃 cookieManager.setAcceptCookie(true); cookieManager.removeSessionCookie();//移除 cookieManager.removeAllCookie(); //base64加密// String base64Cookies = Base64Utils.encodeStr(getCookies()); //根据RFC822规定,BASE64Encoder编码每76个字符,还需要加上一个回车换行。 //使用 commons-codec-1.10.jar 不会换行而且效率更高 //这里我使用的是sun.misc.BASE64Decoder.jar,每76个字符会换行,所以下面去掉换行,为什么不用上面的呢,使用commons-codec-1.10.jar,Android Studio编译提示方法重复,没找到解决办法。// base64Cookies = base64Cookies.replace("\n", "");// Log.i("base64Cookies:", base64Cookies); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, 7); String expiresTime = calendar.getTime().toGMTString(); Log.i("expiresTime =", expiresTime); //分开设置,不然只会设置第一个分号之前的cookie// cookieManager.setCookie(host, "Token=" + base64Cookies); //不加密 cookieManager.setCookie(host, "Token=" + cookies); //注意host的值,类似于这个网址:http://www.jianshu.com/writer#/notebooks/2498434/notes/4304102/preview,host可以取:www.jianshu.com或者.jianshu.com,注意作用域,不要把整个url都放上了。 cookieManager.setCookie(host, "Domain=" + host); cookieManager.setCookie(host, "Path=/"); // Expires变量是一个只写变量,它确定了Cookie有效终止日期。该属性值DATE必须以特定的格式来书写: // 星期几,DD-MM-YY HH:MM:SS GMT,GMT表示这是格林尼治时间。反之,不以这样的格式来书写,系统将无法识别。 // 该变量可省,如果缺省时,则Cookie的属性值不会保存在用户的硬盘中,而仅仅保存在内存当中,Cookie文件将随着浏览器的关闭而自动消失。 cookieManager.setCookie(host, "Expires=" + expiresTime); CookieSyncManager.getInstance().sync(); String newCookie = cookieManager.getCookie(host); if (newCookie != null) { Log.i("getCookie:", newCookie); } } catch (Exception e) { Log.e("failedCookie=%s", e.toString()); } }
3.自定义scheme、js交互传值、调用js方法及document对象
例如:登录scheme为 goto://just/loginref=http://www.baidu.com&callback=loginWeb webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { //1.登录scheme url = goto://just/login?callback=loginWeb if (url.startsWith("goto://just/login")) { //登录,跳转到native得LoginActivity //成功后在onActivityResult()方法中执行js的回调方法loginWeb传toekn值给H5 return true; //2.跳转新activity scheme url = goto://just/newweb?ref=http://www.baidu.com } else if (url.startsWith("goto://just/newweb")) { //页面加载不在本页webview加载,而是新打开此MainActivity(标准模式,为了循环复用) String ref = "http://www.baidu.com"; Intent intent = new Intent(MainActivity.this, MainActivity.class); intent.putExtra("webUrl", ref); startActivity(intent); return true; } return super.shouldOverrideUrlLoading(view, url); } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); //页面错误 llError.setVisibility(View.VISIBLE); } public void onPageFinished(WebView view, String url) { Log.d("WebView", "onPageFinished "); //获取整个页面的Html view.loadUrl("javascript:window.weixinObj.getHtml('<head>'+" + "document.getElementsByTagName('html')[0].innerHTML+'</head>');"); //通过document.title 获取页面的title view.loadUrl("javascript:window.weixinObj.getTitle(document.title)"); //此方法也可以通过document.title 获取标题,但是需要Api19才能使用// view.evaluateJavascript("document.title", new ValueCallback<String>() {// @Override// public void onReceiveValue(String title) {//// }// }); super.onPageFinished(view, url); } }); @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //登录页返回后执行 String callback = "loginWeb"; synCookies(this, host, cookies); webView.loadUrl("javascript:" + callback + "('" + cookies + "')"); webView.reload(); } private class InterfaceObject { @JavascriptInterface public void getHtml(String html) { //获取html的内容 } @JavascriptInterface public void getTitle(String title) { //获取标题 } }
4.以上是我在项目中使用到的一些交互,经过测试是可用的,其实上面写的这些网上有很多,但是比较分散,我就自己总结了一下,例子无法运行的(没有调试,可能有些逻辑错误),因为没有网页测试,如果使用本地html的也不好模拟网络上环境,所以只写了一些逻辑,需要大家自行写h5测试。
资源:Example下载

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software