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的时候
在这里插入图片描述

有js的时候
在这里插入图片描述
PS:大家可以根据网页获取到指定内容,使用js使其隐藏

发布了1080 篇原创文章 · 获赞 845 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/104002322