繁体   English   中英

Android webview,在assets文件夹中加载javascript文件

[英]Android webview, loading javascript file in assets folder

我已经看过很多次这个问题,但仍然无法让我的代码工作。

我希望我的webview加载一些URL(例如www.google.com),然后应用存储在assets/jstest.js一些javascript,其中包含以下内容:

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

这是我尝试加载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); "
                + "})()"); 
} 

我知道这里的javascript有效,因为背景颜色实际上变为红色,但由于某种原因它不会加载jstest.js 我认为问题可能在文件路径中(我确定javascript代码的每一行都是正确的),但它看起来对我来说是正确的。 该文件位于正确的文件夹中。

我错过了什么?

编辑

由于WebResourceResponse类仅适用于API Level 11,所以这是我最终想到的。

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 + ")()"); 
    } 

jstest.js只包含:

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

我尝试了同样的事情,将bookmarklet(你的loadUrl()调用中的javascript代码)加载到第三方页面。 我的bookmarklet还依赖于其他资源(javascript和css文件),这些资源不会加载文件:/// android_asset URL。

这是因为页面的安全上下文仍然是例如http://www.google.com的安全上下文,并且不允许访问文件:URL。 如果提供/覆盖WebChromeClient.onConsoleMessage(),您应该能够看到错误。

我最终得到了一个kludge,我将bookmarklet的资产引用更改为伪造的URL方案,如:

asset:foo/bar/baz.js

并添加了一个WebViewClient.shouldInterceptRequest()覆盖,它会查找这些内容并使用AssetManager.open()从资产中加载它们。

我不喜欢这个问题的一件事是,资产:方案对我的视图加载的任何页面上的任何第三方HTML / Javascript开放,使他们可以访问我的应用程序的资产。

我没有尝试的另一种方法是使用数据:URL来将子资产嵌入书签中,但这可能会变得难以处理。

我更喜欢它,如果有操纵只是 JS书签我加载在使用loadURL()的安全上下文的方式,但我找不到这样的事情。

这是一个片段:

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;
        }
    }

我认为cordova的iceam cream webview客户端可以做你想做的事情。

如果在某处记录这将是很好的,但据我所知,它不是。

看看cordova的android github: https//github.com/apache/incubator-cordova-android/blob/master/framework/src/org/apache/cordova/IceCreamCordovaWebViewClient.java

这是我最终如何做到这一点。 我使用Content://协议并设置contentprovider来处理将文件描述符返回给系统

这是我的fileContentProvider:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;


import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.util.Log;

public class FileContentProvider extends ContentProvider {
    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) {

        Log.d("FileContentProvider","fetching: " + uri);

        ParcelFileDescriptor parcel = null;

        String fileNameRequested = uri.getLastPathSegment();
        String[] name=fileNameRequested.split("\\.");
        String prefix=name[0];
        String suffix=name[1];
       // String path = getContext().getFilesDir().getAbsolutePath() + "/" + uri.getPath();
        //String path=file:///android_asset/"+Consts.FILE_JAVASCRIPT+"

/*check if this is a javascript file*/

        if(suffix.equalsIgnoreCase("js")){
        InputStream is = null;
        try {
            is = getContext().getAssets().open("www/"+Consts.FILE_JAVASCRIPT);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


        File file = stream2file(is,prefix,suffix);
        try {
            parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        } catch (FileNotFoundException e) {
            Log.e("FileContentProvider", "uri " + uri.toString(), e);
        }
        }
        return parcel;
    }

    /*converts an inputstream to a temp file*/

    public File stream2file (InputStream in,String prefix,String suffix) {
        File tempFile = null;
        try {
            tempFile = File.createTempFile(prefix, suffix);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        tempFile.deleteOnExit();

            FileOutputStream out = null;
            try {
                out = new FileOutputStream(tempFile);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

            try {
                IOUtils.copy(in, out);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        return tempFile;
    }


    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public int delete(Uri uri, String s, String[] as) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public String getType(Uri uri) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public Uri insert(Uri uri, ContentValues contentvalues) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public Cursor query(Uri uri, String[] as, String s, String[] as1, String s1) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public int update(Uri uri, ContentValues contentvalues, String s, String[] as) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }
}

在清单中我定义了提供者:

<provider android:name="com.example.mypackage.FileContentProvider"
          android:authorities="com.example.fileprovider"
        />

这是注入webview的javascript o:

webView.loadUrl("javascript:(function() { "

           + "var script=document.createElement('script'); "
           + " script.setAttribute('type','text/javascript'); "
           + " script.setAttribute('src', 'content://com.example.fileprovider/myjavascriptfile.js'); "
      /*      + " script.onload = function(){ "
           + "     test(); "
           + " }; "
      */     + "document.body.appendChild(script); "
           + "})();");

这是myjavascriptfile.js(作为示例):

   function changeBackground(color) {
       document.body.style.backgroundColor = color;
   }

给出以下两个条件:

  • minSdkVersion 21
  • targetSdkVersion 28

我可以通过以下Java代码成功加载任何本地资产(js,png,css)

@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
    Uri uri = request.getUrl();
    if (uri.getHost().equals("assets")) {
        try {
            return new WebResourceResponse(
                URLConnection.guessContentTypeFromName(uri.getPath()),
                "utf-8",
                MainActivity.this.getAssets().open(uri.toString().substring(15)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

在我可以使用的HTML代码中

<link rel="stylesheet" href="https://assets/material.min.css">
<script src="https://assets/material.min.js"></script>
<script src="https://assets/moment-with-locales.min.js"></script> 
<img src="https://assets/stackoverflow.png">

在Java中,以下也适用(您还需要向资产添加favicon.ico

webView.loadUrl("https://assets/example.html");

使用https://作为方案允许我从通过HTTPS提供的页面加载本地资产,而不会因混合内容而导致安全问题。

这些都不需要设置:

webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
webSettings.setDomStorageEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);    

也许你可以把资产作为'html / javascript模板'。 您可以将这些文本源和字符串逻辑中的不同组合在一起,以组成要加载到WebViewer中的所需html。 然后,使用.loadData而不是.loadUrl

我自己使用它似乎工作得很好。

希望能帮助到你!

暂无
暂无

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

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