Android的web视图,加载JavaScript资产文件夹文件 [英] Android webview, loading javascript file in assets folder

查看:186
本文介绍了Android的web视图,加载JavaScript资产文件夹文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这个问题已经被问过很多次,但还是不能设法得到我的code工作。

我希望我的的WebView 的加载一些URL(比如www.google.com),然后申请一些JavaScript存储在资产/ jstest.js ,它包含以下内容:

 函数test(){
document.bgColor =#00FF00; //变为绿色的背景颜色
}
 

和这里的地方我尝试加载JS:

  @覆盖
公共无效onPageFinished(web视图查看,字符串URL){
    view.loadUrl(JavaScript的:(函数(){
                +document.bgColor ='#FF0000'; //变为红色的背景颜色
                +VAR脚本= document.createElement方法('脚本');
                +script.setAttribute('类型','文字/ JavaScript的');
                +script.setAttribute('src'中,'文件:///android_asset/jstest.js');
                +script.onload =功能(){
                +测试();
                +};
                +document.getElementsByTagName(头)[0] .appendChild(脚本);
                +})());
}
 

我知道这里的​​JavaScript的作品,因为背景颜色居然变成红色,但由于某些原因,它不会加载 jstest.js 。我认为这个问题可能是文件路径(我敢肯定的JavaScript的code每隔一行是正确的),但它看起来正确的给我。而该文件是在正确的文件夹。

我在想什么?

修改

由于 WebResourceResponse 类是仅适用于API级别11,这里就是我到底想通了。

 公共无效onPageFinished(web视图查看,字符串URL){
        字符串jscontent =;
        尝试{
            InputStream的是= am.open(jstest.js); // AM = Activity.getAssets()
            InputStreamReader的ISR =新InputStreamReader的(是);
            的BufferedReader BR =新的BufferedReader(ISR);

            串线;
            而((行= br.readLine())!= NULL){
                jscontent + =行;
            }
            is.close();
        }
        赶上(例外五){}
        view.loadUrl(javascript的:(+ jscontent +)());
    }
 

jstest.js 单纯地包含:

 函数(){
    document.bgColor =#00FF00;
}
 

解决方案

我想同样的事情,加载书签(javascript的code在使用loadURL()调用)到第三方网页。我的书签还取决于其他资产(JavaScript和CSS文件),这将与文件不加载:/// android_asset网址

这是因为网页的安全上下文仍然是,例如, http://www.google.com ,而这不允许访问的文件:网址。你应该可以看到错误,如果你提供/重写WebChromeClient.onConsoleM​​essage()。

我结束了一个杂牌组装电脑,我改变了书签的资产引用虚假URL方案,如:

 资产:富/酒吧/ baz.js
 

和加入了WebViewClient.shouldInterceptRequest()重写看起来对于那些并加载它们的资产使用AssetManager.open()。

一件事,我不喜欢这种杂牌是资产:计划是开放给任何页面我的看法加载任何第三方的HTML / Javascript中,使他们能够享受我的应用程序的资产

一种选择,这是我没有尝试,将使用数据嵌入子资产的书签:网址,但可以得到笨拙

我更preFER,如果有一种方式来操作的安全上下文中的只是 JS的书签我加载在使用loadURL(),但我无法找到任何东西这样的。

下面是一个片断:

 进口android.webkit.WebResourceResponse;
...
    私人final类FooViewClient扩展WebViewClient
    {
    私人最终字符串书签;
    私人最终字符串格式;

    私人FooViewClient(字符串书签,字符串格式)
        {
        this.bookmarklet =书签;
        this.scheme =计划;
        }

    @覆盖
    公共无效onPageFinished(web视图查看,字符串URL)
        {
        view.loadUrl(书签);
        }

    @覆盖
    公共WebResourceResponse shouldInterceptRequest(web视图查看,字符串URL)
        {
        如果(url.startsWith(方案))
            尝试
                {
                返回新WebResourceResponse(url.endsWith(JS)文/ JavaScript的:文本/ CSS,UTF-8,
                        Foo.this.getAssets()开(url.substring(scheme.length())))。
                }
            赶上(IOException异常E)
                {
                Log.e(的getClass()getSimpleName(),e.​​getMessage(),E。);
                }

        返回null;
        }
    }
 

I've seen this question has been asked a lot of times, but still can't manage to get my code working.

I want my webview to load some URL (say www.google.com) and then apply some javascript stored in assets/jstest.js, which contains the following:

function test(){
document.bgColor="#00FF00"; //turns to green the background color
}

And here's where I try to load the JS:

@Override  
public void onPageFinished(WebView view, String url){
    view.loadUrl("javascript:(function() { "
                + " document.bgColor='#FF0000';" //turns to red the background color
                + " var script=document.createElement('script'); "
                + " script.setAttribute('type','text/javascript'); "
                + " script.setAttribute('src', 'file:///android_asset/jstest.js'); "
                + " script.onload = function(){ "
                + "     test(); "
                + " }; "
                + " document.getElementsByTagName('head')[0].appendChild(script); "
                + "})()"); 
} 

I know the javascript here works because the background color actually turns to red, but for some reason it won't load jstest.js. I think the problem might be in file path (I'm certain every other line of the javascript code is correct), but it looks correct to me. And the file is in the right folder.

What am I missing?

EDIT:

Since WebResourceResponse class is available only with API Level 11, here's what I've figured out in the end.

public void onPageFinished(WebView view, String url){
        String jscontent = "";
        try{
            InputStream is = am.open("jstest.js"); //am = Activity.getAssets()
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            String line;
            while (( line = br.readLine()) != null) {
                jscontent += line;
            }
            is.close(); 
        }
        catch(Exception e){}
        view.loadUrl("javascript:(" + jscontent + ")()"); 
    } 

with the jstest.js simply containing:

function() {
    document.bgColor="#00FF00";
}

解决方案

I tried the same thing, loading a bookmarklet (the javascript code in your loadUrl() call) into a third-party page. My bookmarklet also depends on other assets (javascript and css files) which would not load with a file:///android_asset URL.

That's because the security context of the page is still that of, e.g., http://www.google.com, and that's not allowed access to file: URLs. You should be able to see the errors if you supply/override a WebChromeClient.onConsoleMessage().

I ended up with a kludge where I changed the bookmarklet's asset references to a bogus URL scheme, like:

asset:foo/bar/baz.js

and added a WebViewClient.shouldInterceptRequest() override which looks for those and loads them from assets using AssetManager.open().

One thing I don't like about this kludge is that the asset: scheme is open to any third-party HTML/Javascript on any page my view loads, giving them access to my app's assets.

One alternative, which I didn't try, would be to embed the sub-assets in the bookmarklet using data: URLs, but that can get unwieldy.

I'd much prefer it if there was a way to manipulate the security context of just the JS bookmarklet I'm loading in loadUrl(), but I can't find anything like that.

Here's a snippet:

import android.webkit.WebResourceResponse;
...
    private final class FooViewClient extends WebViewClient
    {
    private final String bookmarklet;
    private final String scheme;

    private FooViewClient(String bookmarklet, String scheme)
        {
        this.bookmarklet = bookmarklet;
        this.scheme = scheme;
        }

    @Override
    public void onPageFinished(WebView view, String url)
        {
        view.loadUrl(bookmarklet);
        }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url)
        {
        if (url.startsWith(scheme))
            try
                {
                return new WebResourceResponse(url.endsWith("js") ? "text/javascript" : "text/css", "utf-8",
                        Foo.this.getAssets().open(url.substring(scheme.length())));
                }
            catch (IOException e)
                {
                Log.e(getClass().getSimpleName(), e.getMessage(), e);
                }

        return null;
        }
    }

这篇关于Android的web视图,加载JavaScript资产文件夹文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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