Android Webview HTML Loading Javascript Problem

后端 未结 2 918
囚心锁ツ
囚心锁ツ 2021-01-05 09:06

I\'ve been battling this problem for over 48 hours now and I have been unable to find an answer anywhere on the net. Here\'s the setup:

My Android application is do

相关标签:
2条回答
  • 2021-01-05 09:44

    The preferred way to to load a html which references js, css is to use

    webView.loadDataWithBaseURL()
    

    We need to pass the root directory of the location where the html,js,css are found on the file system as the baseURL. Important thing to note here is that we need to use "file" scheme URL only.

    In your case code should be

        String html = readFileAsString(
           new FileInputStream("file://" + contentLocation + url) );
    webView.loadDataWithBaseURL("file://" + contentLocation,html,"text/html","utf-8",null);
    
    
    public static StringBuffer streamToString(InputStream stream ){
    
            StringBuffer fileContent = new StringBuffer("");
            try {
    
                int size = stream.available();
                byte[] buffer = new byte[size];
                int length;
                while ((length = stream.read(buffer)) != -1) {
                    fileContent.append(new String(buffer));
                }
                stream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                try {
                    stream.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
    
            return fileContent;
        }
    

    Hope the answer helps future visitors

    PS: The above code snippet is not compiled

    0 讨论(0)
  • 2021-01-05 09:51

    Was never able to find a solution to this.

    I ended up just editing the HTML files, such that changed the Javascript source files to inline Javascript. That worked (as I expected it would).

    0 讨论(0)
提交回复
热议问题