文档章节

Android WebView

CrazyManDF
 CrazyManDF
发布于 2017/05/07 09:28
字数 580
阅读 100
收藏 1

WebView内存泄漏

private void initView() {

        LinearLayout llRoot = findViewById(R.id.ll_root);

        wvShow = new WebView(getApplicationContext());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        wvShow.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        llRoot.addView(wvShow,params);
    }

    private void setupView() {
        WebSettings settings = wvShow.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setDefaultTextEncodingName("utf-8");
        String url = "";
        wvShow.loadUrl(url);
    }

    @Override
    protected void onDestroy() {
        if (wvShow != null) {
            ViewParent viewParent = wvShow.getParent();
            if (viewParent != null){
                ((ViewGroup)viewParent).removeView(wvShow);
            }
            wvShow.stopLoading();
            wvShow.getSettings().setJavaScriptEnabled(false);
            wvShow.clearHistory();
            wvShow.removeAllViews();
            wvShow.destroy();
        }
        super.onDestroy();
    }

https://www.jianshu.com/p/3e8f7dbb0dc7

解决跨域的问题

报错:XMLHttpRequest cannot load http://www.xx.com/xx. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access."

Android端:

WebSettings settings = wvShow.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowUniversalAccessFromFileURLs(true);  // 跨域
settings.setDefaultTextEncodingName("utf-8");
wvShow.loadUrl("http://www.xx.com/");

ajax请求


$.ajax({
	url : path,
	type: "POST",
	crossDomain: true, // 跨域配置
	xhrFields: {
		withCredentials: true //发送凭据
	},
	success : function(result) {
	   alert("success");
	}
});

php 允许所有域名访问

header('Access-Control-Allow-Origin:*'); //跨域访问
header("Access-Control-Allow-Credentials: true"); //允许跨域请求中携带cookie	

// 服务器端 Access-Control-Allow-Credentials = true时,参数Access-Control-Allow-Origin 的值不能为 '*'

参考:

webview跨域问题解决方案 http://blog.csdn.net/yclfdn2004/article/details/51364660

跨域Ajax请求时是否带Cookie的设置 http://blog.csdn.net/wzl002/article/details/51441704

前后端分离的web项目,ajax跨域请求后端携带cookie https://my.oschina.net/qinghang/blog/1608792

http://blog.hellofe.com/web/2014/12/28/the-CORS-protocol/

Android WebView获取网页数据

/**
 * webview加载网页url
 */
private void LoadAuthPageUrl() {

	String url = "xxxxxx";

	wbAuth.setWebChromeClient(new WebChromeClient(){

		[@Override](https://my.oschina.net/u/1162528)
		public void onReceivedTitle(WebView view, String title) {
			super.onReceivedTitle(view, title);
			Log.d(TAG, "==" + title);
		}
	});
	wbAuth.setWebViewClient(new WebViewClient(){

		[@Override](https://my.oschina.net/u/1162528)
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			view.loadUrl("javascript:(function() { " + jsFormInjectCode + "})()"); //注入javascript
		}

		[@Override](https://my.oschina.net/u/1162528)
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url); 
			return true;
		}

		[@Override](https://my.oschina.net/u/1162528)
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			Log.d(TAG, "==" +errorCode + "=" + description + "=" +failingUrl);
		}
	});
	// 将FormDataInterface类中的processFormData方法映射到javascript中的window.FORMOUT.processFormData(data);
	wbAuth.addJavascriptInterface(new FormDataInterface(), "FORMOUT"); 
	WebSettings settings = wbAuth.getSettings();
	settings.setJavaScriptEnabled(true);  // 支持javascript
	settings.setDefaultTextEncodingName("utf-8");
	wbAuth.loadUrl(url); // 加载网页url
	//wbAuth.loadDataWithBaseURL(url, data,  "text/html", "utf-8", null); // 直接加载html字符串,第一个url是html种资源获取的根路径
}


 /**
 * javascript的交互类
 */
private class FormDataInterface {

	@JavascriptInterface
	public void processFormData(String formData) {
		// 获取到的值:
		// method=post&action=xx&response_type=code&redirect_uri=xxx&username=xxx&password=xxx
		Log.d(TAG, "====" + formData);
		
	}

}

// 注入的javascript代码

String jsFormInjectCode =
	"function parseForm(event) {" +
	" var form = this;" +
	" if (this.tagName.toLowerCase() != 'form')" +
	"   form = this.form;" +
	" var data = '';" +
	" if (!form.method) form.method = 'get';" +
	" data += 'method=' + form.method;" +
	" data += '&action=' + form.action;" +
	" var inputs = document.forms[0].getElementsByTagName('input');" +
	" for (var i = 0; i < inputs.length; i++) {" +
	"   var field = inputs[i];" +
	"   if (field.type != 'submit' && field.type != 'reset' && field.type != 'button')" +
	"       data += '&' + field.name + '=' + field.value;" +
	" }" +
	" window.FORMOUT.processFormData(data);" +
	"}" +
	"" +
	"for (var form_idx = 0; form_idx < document.forms.length; ++form_idx)" +
	"       document.forms[form_idx].addEventListener('submit', parseForm, false);" +
	"var inputs = document.getElementsByTagName('input');" +
	"for (var i = 0; i < inputs.length; i++) {" +
	"       if (inputs[i].getAttribute('type') == 'button')" +
	"           inputs[i].addEventListener('click', parseForm, false);" +
	"}";

[参照]https://gist.github.com/adrobisch/734117

© 著作权归作者所有

共有 人打赏支持
CrazyManDF
粉丝 3
博文 77
码字总数 30000
作品 0
程序员
如何获取WebView的内容宽度[翻译]

原文网址:http://android.pimmos.com/2011/03/24/how-to-retrieve-the-contentwidth-of-a-webview/ The extensive Android SDK allows you to do many great things with particular views ......

拉风的道长
2013/04/23
0
5
Android的WebView与ProgressDialog结合

WebView组件支持直接加载网页,可以将其视为一个浏览器,要实现该功能,具体步骤如下: webview.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:o...

墙头草
2011/08/05
0
0
WebView深度学习(一)之WebView的基本使用以及Android和js的交互

前言:随着市场需求的不断变化,原生安卓已经无法满足客户的需要了,现在很多app都在使用Android和h5的交互实现某些功能,比如商品详情页,文章详情页面,商品点评页面,还有某些复杂的展示页...

aweiloveandroid
2017/07/01
0
0
Android UI开发之WebView简单使用

If you want to deliver a web application (or just a web page) as a part of a client application, you can do it using WebView. The WebView class is an extension of Android's View......

秋风醉了
2014/06/17
0
0
android WebView详解

浏览器控件是每个开发环境都具备的,这为马甲神功提供了用武之地,windows的有webbrowser,android和ios都有webview。只是其引擎不同,相对于微软的webbrowser,android及ios的webview的引擎...

amigos_wu
2012/06/25
0
1

没有更多内容

加载失败,请刷新页面

加载更多

命令行新建Maven多项目

参考地址 # DgroupId 可以理解为包名# DartifactId 可以理解为项目名mvn archetype:generate -DgroupId=cn.modfun -DartifactId=scaffold -DarchetypeArtifactId=maven-archetype-quickst......

阿白
41分钟前
1
0
OSChina 周四乱弹 —— 上帝对我单身年限的惩罚越来越长了

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @达尔文:分享张卫健的单曲《身体健康》 《身体健康》- 张卫健 手机党少年们想听歌,请使劲儿戳(这里) 昨天是重阳节咯, 可惜小小编辑总是晚...

小小编辑
43分钟前
7
0
django rest framework 外键序列化方法与问题总结

django rest framework 外键序列化方法与问题总结 当借口中需要出现一对多关系的时候,我们可以用rest_framwork的序列化功能来处理,代码如下. # models.pyfrom django.db import modelscl...

_Change_
昨天
1
0
SingleNumber136 leetCode

Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you im......

woshixin
昨天
1
0
String ,  StringBuffer ,  StringBuilder的区别

String , StringBuffer , StringBuilder的区别 String 首先,String 是用来表示一个字符串常量的,它是一个不可变对象,意味着,一旦我们创建了某个字符串之后,就不能再改变它的值了,我们可...

tsmyk0715
昨天
6
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部