HTML加载之前的Andr​​oid的WebView注入的Javascript [英] Android WebView Inject Javascript before html loaded

查看:369
本文介绍了HTML加载之前的Andr​​oid的WebView注入的Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Android的WebView加载某些网页。我需要插入一段JavaScript code到所有页面加载它们之前。

I am using Android WebView to load some web pages. I need insert a piece of Javascript code to all the pages before they loaded.

我试图注入他们WebViewClient onPageStart回调。

I am trying to inject them on WebViewClient onPageStart callback.

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient(){

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        loadUrl("javascript:var output='test string';");
        }
})

mWebView.loadUrl("xxx.html");

HTML code:

HTML code:

<html>
<script>document.write(output);</script>
</html>

我希望我的js code HTML之前加载。但有时HTML后,JS code加载。

I expected My Js code loaded before HTML. But sometimes the JS code loaded after HTML.

有什么办法可以解决我的问题?

Is there any way could solve my issue?

推荐答案

怎么样通过JavaScript加载页面?

What about loading your page via javascript ?

在你的资产,包括你的脚本加上这个小功能创建一个空白的HTML页面(我使用jQuery为简单起见,在这里,但你可以使用其他的框架或框架没有在所有)。

Create a blank html page in your assets, that include your script plus this little function (I'm using jquery for the sake of simplicity here, but you can use another framework or not framework at all).

window.loadPage = function (url) {
    $.get(url, function(page) {
        $('html').replace(page);
    });
};

然后,在你的Andr​​oid应用程序:

Then, on your android app :

mWebView.loadUrl("javascript: loadPage('xxx.html')");

注:我没有注意到xxx.html可以在您的资产也并没有在Web服务器上的某个地方,在这种情况下,阿贾克斯查询将失败出于安全原因,但你可以忘记Ajax请求,念你的HTML从你的Andr​​oid应用程序字符串页面,并把它作为参数传递给略加修​​改的JavaScript函数。

Note : I didn't notice xxx.html could be in your assets too and not in a web server somewhere, in that case the ajax query will fail for security reasons, but you can forget the ajax request, read you html page in String from your android app and pass it as an argument to a slightly modified javascript function.

这篇关于HTML加载之前的Andr​​oid的WebView注入的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆