Inject javascript file to my site with webview in android

后端 未结 2 1989
夕颜
夕颜 2021-01-06 05:55

I want to inject javascript file to my site. My site is a simple html page that is on server. I have injected css file. (with Manish\'

2条回答
  •  悲&欢浪女
    2021-01-06 06:31

    Some refinements to previous answer. Suppose we use Cyrillic words. Result would be a garbaged strings. It's not good. With code below you can use non-english chars in content. Just add additional url-encoding/decoding to your code and you good to go. Reedited version below.

    private void injectJS() {
        try {
            InputStream inputStream = getAssets().open("jscript.js");
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();
    
            // preserve non-english letters
            String uriEncoded = URLEncoder.encode(new String(buffer, "UTF-8"), "UTF-8").replace("+", "%20");
    
            String encoded = Base64.encodeToString(uriEncoded.getBytes(), Base64.NO_WRAP);
            webView.loadUrl("javascript:(function() {" +
                    "var parent = document.getElementsByTagName('head').item(0);" +
                    "var script = document.createElement('script');" +
                    "script.type = 'text/javascript';" +
                    // don't forget to use decodeURIComponent after base64 decoding
                    "script.innerHTML = decodeURIComponent(window.atob('" + encoded + "'));" +
                    "parent.appendChild(script)" +
                    "})()");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题