前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WebView重写onJsAlert那些事

WebView重写onJsAlert那些事

作者头像
技术小黑屋
发布2018-09-04 16:43:43
3.5K0
发布2018-09-04 16:43:43
举报
文章被收录于专栏:技术小黑屋技术小黑屋

本文主要将如何重写onJsAlert,让烦人的对话框变为无干扰的Toast,以及为什么onJsAlert只调用一次的问题.

什么是Javascript Alert

Alert是一种提示信息或者警告信息的对话框,一旦显示到用户面前,只能点击OK才能关闭.

通常一般的实现类似

1 2 3 4 5

<html> <SCRIPT type="text/javascript"> alert('This is alert dialog !') </SCRIPT> </html>

对应的效果图:

onJsAlert API 介绍

public boolean onJsAlert (WebView view, String url, String message, JsResult result) Added in API level 1 Tell the client to display a javascript alert dialog. If the client returns true, WebView will assume that the client will handle the dialog. If the client returns false, it will continue execution. Parameters view The WebView that initiated the callback. url The url of the page requesting the dialog. message Message to be displayed in the window. result A JsResult to confirm that the user hit enter. Returns boolean Whether the client will handle the alert dialog.

重写为Toast展示

其实Alert,只是提示信息,而且这个提示信息还是阻塞其他操作的,为什么我们不适用一个长时间显示的Toast呢?

下面示范一下如何换成Toast.

1 2 3 4 5 6 7

@Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.i("MainActivity", "onJsAlert url=" + url + ";message=" + message); Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); result.confirm(); return true; }

为什么onJsAlert只调用了一次

如果你没有参考上述部分或者没有留意,有时候你会发现onJsAlert只调用了一次,为什么呢,实际上,你可能忽略了一句调用.就是处理JsResult.

public final void cancel () Added in API level 1 Handle the result if the user cancelled the dialog. public final void confirm () Added in API level 1 Handle a confirmation response from the user.

你需要调用result.confirm()或者result.cancel()来处理jsResult,否则会出问题.

demo下载

延伸阅读:

http://www.w3schools.com/js/js_popup.asp http://developer.android.com/reference/android/webkit/JsResult.html

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 什么是Javascript Alert
  • onJsAlert API 介绍
  • 重写为Toast展示
  • 为什么onJsAlert只调用了一次
  • demo下载
  • 延伸阅读:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档