Android保存WebView HTML源码

2023-12-26 11:58:24
import android.content.Context;
import android.util.Log;
import com.example.MyApplication;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;


public class JavascriptInterface {
    @android.webkit.JavascriptInterface
    public void onReceivedSource(String source) {
        Log.d("WebViewSource", source);
        saveHtmlToFile(source, "saveFile");
    }

    private void saveHtmlToFile(String htmlContent, String fileName) {
        try {
            // 获取应用的 data 目录
            Context context = MyApplication.getContext();
            String filePath = context.getFilesDir().getPath() + "/" + fileName;

            // 使用 FileOutputStream 和 OutputStreamWriter 将 HTML 写入文件
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
            outputStreamWriter.write(htmlContent);
            outputStreamWriter.close();
            Log.e("saveHtmlToFile", "okokoko");
            // 提示保存成功
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}

WebActivity设置

 webView.addJavascriptInterface(new JavascriptInterface(), "javaInterface");

 webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
		  webView.loadUrl("javascript:window.javaInterface.onReceivedSource(document.documentElement.outerHTML);");                
            }
}

文章来源:https://blog.csdn.net/Me_Ordinary/article/details/135217048
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。