webview处理网页对话框

给一个项目中的webview页面提示框优化处理:

  • 之前显示的是这样:
    </div>
    <img src="http://upload-images.jianshu.io/upload_images/3154077-fb19cf86b9cc64a3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width = "200" height = "200" alt="网页效果" align=center />
    </div>
  • 现在的效果:
    </div>
    <img src="http://upload-images.jianshu.io/upload_images/3154077-6a792d7ff141b9f5.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width = "200" height = "200" alt="原生效果" align=center />
    </div>

可以看到标题的样式发生了改变,其实我们可以改变对话框里所有的内容.

处理方法:

private class MyWebChromeClient extends WebChromeClient {
 
        @Override
        public boolean onJsConfirm(WebView view, String url, final String message, final JsResult result) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("温馨提示:")
                            .setMessage(message)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    result.confirm();//这里必须调用,否则页面会阻塞造成假死
                               //     mWebView.reload();//重新刷新页面
                                }
                            })
                            .setNegativeButton("取消",new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    result.cancel();
                                }
                            })
                            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface dialogInterface) {
                                    result.cancel();
                                }
                            })
                            .show();
                }
            });

            return true;
        }

    }

关键点

  • 自定义ChromClient,设置在webview中
  • 之前看文章说是在onJsAlert方法中,加入自己写的AlertDialog,但是没效果,断点也进不去,后来我在onJsConfirm方法中加载了这个AlertDialog,发现效果实现了.
  • 重中之重:记得在取消和确认的时候处理result,并且如果AlertDialog是点击外部取消的话,也要处理result在cancel掉的结果,否则会造成webview页面塞假死
  • 可能会需要AppCompat的主题,之前我用5.1的Theme.noActionBar之类的主题,崩溃了,现在是Theme.AppCompat.Light

抓取网页代码

<a href="https://www.nhw360.com/wishlist/xxx/xxx/" onclick="return confirmRemoveWishlistItem();" title="删除项目" class="btn-remove btn-remove2">取消收藏</a>
function confirmRemoveWishlistItem() {
            return confirm('您是否确认要从我的收藏中删除该产品?');
        }

可以看到js代码是调用了confirm方法的,所以我们在onJsAlert方法设置无效,所以大家可以多试试,有时候也许前端写的代码是alert的,那我们在onJsConfirm中设置肯定是无效的.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容