Android WebView
Android WebView
CrazyManDF 发表于10个月前
Android WebView
  • 发表于 10个月前
  • 阅读 61
  • 收藏 1
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

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

  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 3
博文 73
码字总数 25403
×
CrazyManDF
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: