Android load external local javascript file into WebView
In Android 2.2 WebView I load a local html file that has a link to a JavaScript file (lives in the same folder as the html file). The local html file successfully loads but the referenced JavaScript local file does not and I get this error in LogCat log:
03-25 16:48:57.965: ERROR/Web Console(10865): SyntaxError: Parse error at file:///data/data/com.mydomain.myapp/test.js:91
The line number for the error is the last line for the file and the path in the error log is the correct path for the js file. Of course everything works as expected in Chrome. Here is snippet of the html file
<html>
<head>
<title>My Title</title>
<meta name = "viewport" content = "width = device-width">
<meta name = "viewport" content = "initial-scale = 1.0">
<script type="text/javascript" src开发者_开发知识库="test.js"></script>
<script type="text/javascript">
button_onclick = function() {};
</script>
I found out that this error is due to how the js file is packaged. The app reads the file from SQLite assets database, on initialization, and writes the read file into the device local file system. The js file is saved in SQLite database as text using Firefox SQLite Manager. When I save the js file in SQLite Manager as a BLOB rather than text then everything works as expected and the WebView is able to load the js file successfully from the device local file system. This does not appear to matter for html files, but for js files the parser is looking for something at the end of the file and if it does not find it then it ignores the js file
I suspect this may be due to missing end of file characters which for some reason as not added when I write the file using java output stream when the asset input stream does not contain the end of file characters.
I would look over the WebView reference in the android docs. From the the Doc:
By default, a WebView provides no browser-like widgets, does not enable JavaScript and web page errors are ignored. If your goal is only to display some HTML as a part of your UI, this is probably fine; the user won't need to interact with the web page beyond reading it, and the web page won't need to interact with the user. If you actually want a full-blown web browser, then you probably want to invoke the Browser application with a URL Intent rather than show it with a WebView
You can however enable it on a webview via setJavaScriptEnabled()
.
Follow the answer Determine element of url from webview shouldOverRideUrlLoading and the link in it.
精彩评论