简体   繁体   English

使用android中的webview将javascript文件注入我的网站

[英]Inject javascript file to my site with webview in android

I want to inject javascript file to my site. 我想将javascript文件注入我的网站。 My site is a simple html page that is on server. 我的网站是一个简单的html页面,在服务器上。 I have injected css file. 我已经注入了css文件。 ( with Manish's help ) 有Manish的帮助

So I can manage my simple html site with CSS now. 所以我现在可以使用CSS管理我的简单html网站。 But I want to manage it with javascript too. 但我也想用javascript来管理它。 My jscript.js file is in asset folder. 我的jscript.js文件位于asset文件夹中。 I want to have full access of javascript on my site. 我想在我的网站上完全访问javascript (Remember that, it is MY site) . (请记住,这是我的网站)。 please write the correct codes for me. 请为我写正确的代码。 Thankx. Thankx。

Here is my MainActivity.java file: 这是我的MainActivity.java文件:

package com.example.z5070.myapplication;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.InputStream;


public class MainActivity extends ActionBarActivity {



        WebView webView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            webView = new WebView(this);
            setContentView(webView);


            webView.getSettings().setJavaScriptEnabled(true);


            webView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageFinished(WebView view, String url) {


                    injectCSS();
                    super.onPageFinished(view, url);
                }
            });


            webView.loadUrl("http://www.example.com/");
        }


        private void injectCSS() {
            try {
                InputStream inputStream = getAssets().open("style.css");
                byte[] buffer = new byte[inputStream.available()];
                inputStream.read(buffer);
                inputStream.close();
                String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
                webView.loadUrl("javascript:(function() {" +
                        "var parent = document.getElementsByTagName('head').item(0);" +
                        "var style = document.createElement('style');" +
                        "style.type = 'text/css';" +
                        "style.innerHTML = window.atob('" + encoded + "');" +
                        "parent.appendChild(style)" +
                        "})()");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }


        }

Add a new method to inject javascript file. 添加一个新方法来注入javascript文件。

 private void injectJS() {
        try {
            InputStream inputStream = getAssets().open("jscript.js");
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();
            String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
            webView.loadUrl("javascript:(function() {" +
                    "var parent = document.getElementsByTagName('head').item(0);" +
                    "var script = document.createElement('script');" +
                    "script.type = 'text/javascript';" +
                    "script.innerHTML = window.atob('" + encoded + "');" +
                    "parent.appendChild(script)" +
                    "})()");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Call both methods: injectCSS() and injectJS() after page finishes loading. 在页面加载完成后调用两种方法:injectCSS()和injectJS()。

webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                injectCSS();
                injectJS();
                super.onPageFinished(view, url);
            }
        });

I hope this solves the problem. 我希望这能解决问题。

Be wary of how onload events defined inside inject js file would behave. 警惕inject js文件中定义的onload事件将如何表现。

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. 只需在代码中添加额外的url编码/解码,就可以了。 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM