Android中在WebView中使用javascript
来源:互联网 发布:中国域名网 编辑:程序博客网 时间:2024/05/21 05:22
默认情况下,在WebView中是不能使用javascript的。可以通过书写下面的代码:
WebView myWebView= (WebView) findViewById(R.id.webview);
WebSettings webSettings= myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
然后就可以使用了。
绑定javascript和Android代码:
例如:你可以在你的应用程序中创建一个类:
publicclass JavaScriptInterface{
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c){
mContext = c;
}
/** Show a toast from the web page */
public void showToast(String toast){
Toast.makeText(mContext, toast,Toast.LENGTH_SHORT).show();
}
}
绑定javascript,定义的接口名称为Android。
WebView webView= (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(newJavaScriptInterface(this),"Android");
然后在你的HTML代码中写:
<inputtype="button"value="Say hello"onClick="showAndroidToast('Hello Android!')"/>
<script type="text/javascript">
function showAndroidToast(toast){
Android.showToast(toast);
}
</script>
注意:绑定的javascript运行在另一个线程中,与创建它的线程不是同一个。
处理页面导航:
默认情况下,当你单击你的WebView页面的链接时,连接到URIs。你可以使用下面的方式连接到你自己的WebView。
WebView myWebView= (WebView) findViewById(R.id.webview);
myWebView.serWebViewClient(newWebViewClient());
如何你想控制更多的点击连接的话,可以重写shouldOverrideUrlLoading()方法,创建自己的WebViewClient:
privateclass MyWebViewClientextends WebViewClient{
@Override
public boolean shouldOverrideLoading(WebView view,String url){
if (Uri.parse(url).getHost().equals("www.example.com")){
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent =new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
return true;
}
}
通过下面的方式来访问历史页:
publicboolean onKeyDown(int keyCode,KeyEvent event){
// Check if the key event was the BACK key and if there's history
if ((keyCode== KeyEvent.KEYCODE_BACK)&& myWebView.canGoBack(){
myWebView.goBack();
return true;
}
// If it wasn't the BACK key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode,event);
}
- Android中在WebView中使用javascript
- android在WebView中使用JavaScript
- 在WebView中使用JavaScript
- WebView中使用javascript
- Android中WebView使用
- Android 中使用WebView
- Android webView中调用JavaScript
- JavaScript在Android的WebView中出现一个问题
- 在WebView中使用JavaScript获取网页内容
- Android中Webview使用自定义的javascript进行回调
- Android中Webview使用自定义的javascript进行回调
- Android中Webview使用自定义的javascript进行回调
- android WebView使用 一 (简单使用在程序中)
- 使用WebView在Android中嵌套html网页
- 关于在android中使用webview 和js交互
- Android 在WebView中调用系统下载的简单使用
- Android中webview的使用
- android 中webView的使用
- 区别shell与makefile中的export
- 为甚莫不是我
- (转)android构建自定义的视图组件onMeasure
- 事件监听篇---第二篇
- FFMPEG转码后得到的MP4必须要加载完才能播放的问题
- Android中在WebView中使用javascript
- Linux常用命令速查备忘
- WPF中的鼠标事件详解
- toipc model
- (转)Android中几种图像特效处理的集锦!!!
- Linux C编程连载【4】-基于TCP/IP的文件传输系统
- maven乱码问题解决
- 网页开发如何弹出式文本(密码)输入框
- 嵌入式硬件平台接口开发