Android中WebView如何加载JavaScript脚本
16lz
2021-12-04
主Activity和XML布局,末尾附上效果图
package com.example.myapplication;import androidx.appcompat.app.AppCompatActivity;import android.os.Build;import android.os.Bundle;import android.util.Log;import android.view.View;import android.webkit.WebChromeClient;import android.webkit.WebSettings;import android.webkit.WebView;import android.widget.Toast;public class MainActivity extends AppCompatActivity { //声明控件 private WebView myWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(null); setContentView(R.layout.activity_main); //找到控件 myWebView = findViewById(R.id.webview1); // 启用javascript myWebView.getSettings().setJavaScriptEnabled(true); myWebView.getSettings().setUseWideViewPort(true); //添加js脚本 myWebView.setWebChromeClient(mSearchChromeClient); myWebView.loadUrl("http://m.baidu.com"); } // 定义WebChromeClient private WebChromeClient mSearchChromeClient = new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { Log.d("SEARCH_TAG", "on page progress changed and progress is " + newProgress); // 进度是100就代表dom树加载完成了 if (newProgress == 100) { //内嵌js脚本 myWebView.loadUrl("JavaScript:function mFunct(){$(\"div#logo\").next().next().next().next().eq(0).style.display='none';}mFunct();"); } } }; }
XML布局
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <WebView android:id="@+id/webview1" android:layout_width="match_parent" android:layout_height="match_parent" /></LinearLayout>
没有js的时候
有js的时候
PS:大家可以根据网页获取到指定内容,使用js使其隐藏
更多相关文章
- android 隐藏ListView滚动条
- 安卓巴士Android开发神贴整理
- Android(安卓)Studio实现代码混淆
- android 复制、粘贴字符串 (判断API 11 )
- android在java代码中绘制矩形框
- Android控件之ImageView,Button, ImageButton
- android 分享功能
- Android支持multiDexEnabled,自建脚本编译
- Android(安卓)Camera Parameters