要想让加载的H5页面中的alert显示出来需要在Android端设置:

1. setJavaScriptEnabled

2. setWebChromeClient

完整代码如下:

package com.example.yunlanlink;

import androidx.appcompat.app.ActionBar;

import androidx.appcompat.app.AlertDialog;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;

import android.content.DialogInterface;

import android.os.Bundle;

import android.util.Log;

import android.view.MenuItem;

import android.webkit.JsResult;

import android.webkit.WebChromeClient;

import android.webkit.WebSettings;

import android.webkit.WebView;

public class DeviceInfo extends AppCompatActivity {

WebView webView;

Context ctx = this;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_device_info);

ActionBar actionBar = getSupportActionBar();

if(actionBar != null){

actionBar.setHomeButtonEnabled(true);

actionBar.setDisplayHomeAsUpEnabled(true);

actionBar.setTitle("设备详情");

}

initWebView();

}

@Override

protected void onDestroy() {

//释放资源

if (webView != null)

webView.destroy();

super.onDestroy();

}

@Override

public boolean onOptionsItemSelected(MenuItem item){

Log.d(AppYunlanLink.TAG, "onOptionsItemSelected: " + item.getItemId());

Log.d(AppYunlanLink.TAG, "onOptionsItemSelected home id " + android.R.id.home);

switch (item.getItemId()){

case android.R.id.home:

this.finish();

// onBackPressed();

return true;

default:

return super.onOptionsItemSelected(item);

}

}

private void initWebView() {

webView = new WebView(this);

WebSettings settings = webView.getSettings();

settings.setJavaScriptEnabled(true);

settings.setBuiltInZoomControls(false);//webview 禁止手势缩放

settings.setSupportZoom(false);

settings.setDisplayZoomControls(false);

settings.setDomStorageEnabled(true); // 开启 DOM storage 功能

settings.setAllowUniversalAccessFromFileURLs(true); // 设置是否允许通过 file url 加载的 Javascript 可以访问其他的源(包括http、https等源)

settings.setAllowFileAccess(true);

settings.setUseWideViewPort(true);

settings.setLoadWithOverviewMode(true);

settings.setDefaultTextEncodingName("UTF-8");

settings.setJavaScriptCanOpenWindowsAutomatically(true);

//响应webview 加载H5页面中的alert函数,否则alert显示不出来

webView.setWebChromeClient(new WebChromeClient() {

@Override

public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

AlertDialog.Builder b = new AlertDialog.Builder(ctx);

b.setTitle("title");

b.setMessage(message);

b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

result.confirm();

}

});

b.create().show();

return true;

}

});

String _url = "file:android_asset/dist/index.html#/device/index";

webView.loadUrl(_url);

setContentView(webView); //调用Activity提供的setContentView将webView显示出来

}

}

相关阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: