从Android中的本地资产加载jQuery以获取远程html页面

Vij*_*jay 9 jquery android webview android-webview

我正在尝试从Android webview中读取存储在资产中的本地javascript文件(jQuery).我不想加载base-url,因为我的图像和html是远程提供的.

总结: - 在Android webview中将本地jQuery(在assets文件夹中)加载到远程加载的页面中.

经过长时间的浏览徒劳无功,我决定在这里提出这个问题.请帮忙.

谢谢!

小智 8

  1. 定义一个类似下面的Javascript接口,它将从assets目录中读取你的jquery文件

    class JavaScriptInterface {
    
        @JavascriptInterface
        public String getFileContents(){
            return readAssetsContent("jquery.js");
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 更新WebView以启用JavaScript并添加先前定义的JavaScriptInterface ...

    webView.getSettings().setJavaScriptEnabled(true);       
    webView.addJavascriptInterface(new JavaScriptInterface(), "android");
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在远程HTML中添加javascript代码片段,通过android JavaScript界面​​读取jquery文件内容...

    <script type="text/javascript">
    var s = document.createElement('script');
    s.innerHTML = window.android.getFileContents();
    document.head.appendChild(s);
    
    //check if jquery is loaded now...
    if(typeof $ != "undefined") {
        $(document).ready(function() {
            $('body').css('background','green');
        });
    } else {
        document.body.innerText = "jQuery NOT loaded";
    }
    </script>
    
    Run Code Online (Sandbox Code Playgroud)