我需要将一些javaScript文件注入加载页面。
我的代码:
@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
super.doUpdateVisitedHistory(view, url, isReload); //To change body of overridden methods use File | Settings | File Templates
mWebView.loadUrl("javascript:(function(){var script = document.createElement('script');script.setAttribute('src', 'file:///android_asset/jquery.js'); script.setAttribute('type', 'text/javascript'); document.body.appendChild(script)})();");
mWebView.loadUrl("javascript:(function(){var script = document.createElement('script');script.setAttribute('src', 'file:///android_asset/rangy-core.js'); script.setAttribute('type', 'text/javascript'); document.body.appendChild(script)})();");
mWebView.loadUrl("javascript:(function(){var script = document.createElement('script');script.setAttribute('src', 'file:///android_asset/rangy-serializer.js'); script.setAttribute('type', 'text/javascript'); document.body.appendChild(script)})();");
mWebView.loadUrl("javascript:(function(){var script = document.createElement('script');script.setAttribute('src', 'file:///android_asset/android.selection.js'); script.setAttribute('type', 'text/javascript'); document.body.appendChild(script)})();");// .
}
但这不起作用=(
将代码更改为
mWebView.loadUrl("javascript:function loadScript(url, callback)" +
"{" +
" var head = document.getElementsByTagName('head')[0];" +
" var script = document.createElement('script');" +
" script.type = 'text/javascript';" +
" script.src = url;" +
" script.onreadystatechange = callback;" +
" script.onload = callback;" +
" head.appendChild(script);" +
"}");
mWebView.loadUrl("javascript:loadScript('file:///android_asset/jquery.js','callback')");
mWebView.loadUrl("javascript:loadScript('file:///android_asset/rangy-core.js','callback')");
mWebView.loadUrl("javascript:loadScript('file:///android_asset/rangy-serializer.js','callback')");
mWebView.loadUrl("javascript:loadScript('file:///android_asset/android.selection.js','callback')");
现在我有错误:06-11 10:24:15.432:错误/ Web控制台(7962):不允许加载本地资源:file:///android_asset/jquery.js at null:0
答案 0 :(得分:1)
您可以使用js方法加载js文件并将url作为参数从java
传递以下是完整的工作示例
[Activity.java]
public class MainActivity extends Activity {
WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new JavaScriptInterface(), "jsinterface");
mWebView.loadUrl("file:///android_asset/sq.html");
}
final class JavaScriptInterface {
JavaScriptInterface() {
}
@JavascriptInterface
public void windowLoaded() {
mWebView.loadUrl("javascript:loadScript('test.js', 'testing')");
Log.i("browser", "browser loaded");
}
}
}
[sq.html]
<html>
<head>
<script>
onload = function () {
window.jsinterface.windowLoaded();
}
//JS
function loadScript(url, callback)
{
console.log("loading script " + url);
// adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// then bind the event to the callback function
// there are several events for cross browser compatibility
//script.onreadystatechange = callback;
script.onload = callback;
// fire the loading
head.appendChild(script);
}
</script>
</head>
<body>replace this
</body>
</html>
资产文件夹中的[test.js]
document.body.innerHTML = "<p>testing</p>";
成功执行webview将通过动态加载test.js来显示测试结果。
答案 1 :(得分:1)
以下是我最终如何做到这一点。我使用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;
}
答案 2 :(得分:0)
您并不真正需要内容提供商。而不是
mWebView.loadUrl(&#34;文件:///android_asset/sq.html");
您可以使用以下内容加载原始html文件。然后该脚本将能够从assets目录
上传test.js.mWebView.loadDataWithBaseURL(&#34; file:/// android_asset /&#34;,data, &#34; text / html&#34;,null,null);