Search code examples
javascriptandroidwebviewmhtml

How to apply a javaScript function on MHTML files in android?


I'm new in coding and now I need some help. I save my webView content with saveWebArchive() method that in kitkat and above this method save webView as mhtml format. Here is my code that I don't have any problem with this part:

File internalStorage = getApplication().getDir("MyArchive",Context.MODE_PRIVATE);
File webUrlPath = new File(internalStorage.getAbsolutePath());
String urlFileName = webUrlPath.toString();

html_path = urlFileName + File.separator + article.Articlehtml.hashCode() +
                    ".mht";
webView.saveWebArchive(html_path);

When I want to load saved files in webView I use Javascript for change font color that for lower of kitkat it works perfectly but for kitkat and above Changes will not apply. Here another part of my code that I have problem with it:

webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);

File file = new File(html_path);
//for Kitkat and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            webView.loadUrl("file:///" + file);
    }
    else {
          String rawData = null;
          try {
               rawData = getStringFromFile(html_url);
          }catch (Exception e){
                //e.printStackTrace();
            }
 webView.loadDataWithBaseURL(null, rawData,"application/x-webarchive-xml","UTF-8", null);
        }

  webView.setWebViewClient(new WebViewClient(){
  public void onPageFinished(WebView view, String url){
         view.setBackgroundColor(Color.parseColor("#212121"));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {        webView.evaluateJavascript("document.body.style.setProperty(\"color\", \"white\");", null);
    } else {
      webView.loadUrl("javascript:document.body.style.setProperty(\"color\", \"white\");");
} 

I expect to apply javaScript for saved webView content for kitkat and above, that's mean I can change font color of the mhtml file after loaded it in a WebView.

Thanks for your attention.


Solution

  • Finally, I find a solution for my problem. It's use of ColorMatrixColorFilter for invert colors when webView is loaded.