Android webview, loading javascript file in assets folder

前端 未结 5 1904
我在风中等你
我在风中等你 2020-11-29 01:09

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.c

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 01:58

    Here is how i ended up doing it. I used the Content:// protocol and set up a contentprovider to handle returning a file descriptor to the system

    Here is my 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");
        }
    }
    

    in the manifest i defined the provider:

    
    

    Here is the javascript o inject into the webview:

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

    and here is the myjavascriptfile.js (as an example):

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

提交回复
热议问题