Android中WebView如何加载JavaScript脚本

主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的时候

Android中WebView如何加载JavaScript脚本

有js的时候

Android中WebView如何加载JavaScript脚本

PS:大家可以根据网页获取到指定内容,使用js使其隐藏

上一篇:C#基础回顾(二)—页面值传递、重载与重写、类与结构体、装箱与拆箱


下一篇:php中foreach中使用&的办法