在加载Android WebView的html之前注入JavaScript

Inject JavaScript before html loaded with Android WebView

本文关键字:注入 JavaScript html 加载 Android WebView      更新时间:2023-09-26

我正在使用Android WebView加载一个简单的HTML页面。HTML依赖于一小段Javascript代码。

我需要在html加载之前注入Javascript。所以我这样做:

public class MainActivity extends Activity {
    WebView mWebView;
    Button mButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView)findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message,JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });

        mButton = (Button)findViewById(R.id.button);
        mButton.setOnClickListener(new myListener());
    }
    class myListener implements OnClickListener{
        int mCount = 1;
        @Override
        public void onClick(View arg0) {
            System.out.println("Load test page=>"+mCount+" times");
            mWebView.loadUrl("javascript:var output='This string is defined before html loaded.'");
            mWebView.loadUrl("file:///android_asset/test.html");
            mCount++;
        }
    }
}
HTML代码:

<html>
<head>
<script>
alert(output);
</script>
<head>
<body>
</body>
</html>

当我第一次点击按钮时,JS和HTML工作正常。但是当我点击按钮再次执行加载时,它失败了。

日志:

Load test page=>1 times
Load test page=>2 times
Uncaught ReferenceError: output is not defined at file:///android_asset/test.html:5
Load test page=>3 times
Uncaught ReferenceError: output is not defined at file:///android_asset/test.html:5

任何建议吗?

这可能看起来像一个冗长的方法,但是你可以让你的android代码写js代码到一个文件,然后在你的html文件中引用该文件吗?