Android保存WebView HTML源码

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);");                
            }
}

你可能感兴趣的:(android,html,前端)