Lets take a look at this for example: Loading existing .html file with android WebView
I load my HTML file but it contains references to other local css and js files. Do I need use the same file:/// URL inside the HTML file?
No, your structure should be like this:
/assets/html/index.html
/assets/scripts/index.js
/assets/css/index.css
Then just do ( Android WebView: handling orientation changes )
//in onCreate() for Activity, or in onCreateView() for Fragment
if(WebViewStateHolder.INSTANCE.getBundle() == null) { //this works only on single instance of webview, use a map with TAG if you need more
webView.loadUrl("file:///android_asset/html/index.html");
} else {
webView.restoreState(WebViewStateHolder.INSTANCE.getBundle());
}
Make sure you add
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
}
Then just use urls
<html>
<head>
<meta charset="utf-8">
<title>Zzzz</title>
<script src="../scripts/index.js"></script>
<link rel="stylesheet" type="text/css" href="../css/index.css">
EDIT:
That particular code will work only if you add the code that I linked
public class WebViewFragment extends Fragment { //could be activity
private enum WebViewStateHolder
{
INSTANCE;
private Bundle bundle;
public void saveWebViewState(WebView webView)
{
bundle = new Bundle();
webView.saveState(bundle);
}
public Bundle getBundle()
{
return bundle;
}
}
#Override
public void onPause()
{
WebViewStateHolder.INSTANCE.saveWebViewState(myWebView);
super.onPause();
}
As for whatever "security issue" you speak of, you didn't share enough data.
According to Rendering HTML in a WebView with custom CSS, you dont have to specify each CSS or JS. Include them in the HTML file itself.
Related
Using webView.loadUrl is working for https site , but not with my local page which is located in /Applications/MAMP/htdocs/test.html
webView.loadUrl("/Applications/MAMP/htdocs/test.html") is not working
webView.loadUrl("http://localhost:8080/test.html"); is not working
Below is the test.html file
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<h2>JS alert Example</h2>
<button onclick="myFunction()" >Try it</button>
<script>
function myFunction (){
Android.showToast("Sample Android toast message");
}
</script>
</body>
</html>
Now I want to load this page using webView .
Below is the mainactivity.java code
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("http://127.0.0.1:8080/test.html");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.addJavascriptInterface(new WebAppInterface (this), "Android");
}
}
Below is my WebInterface java class :
public class WebAppInterface {
private Context context;
public WebAppInterface (Context context){
this.context = context;
}
#JavascriptInterface
public void showToast (String message){
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
}
Now ,I cant understand why it is not loading the web page mentioned in webView.loadUrl . Note: I having given internet permissions in manifest file.
So if the file is local in the device (android phone), you need to have the path of the file. If the file is bundled in the assets, you can open the file like:
webView.loadUrl("file:///android_asset/filename.html");
Or if you can't find it, you can put the file in the raw resources and read the file into a string and then use:
webView.loadData(htmlString, "text/html", "utf-8");
In any case, most probably the problem you have is you can't find the file. So make sure you are placing the file in the proper place in the assets, or resources. And you are accessing the file correctly.
Here is the documentation on how to access the resources:
https://developer.android.com/guide/topics/resources/providing-resources
If what you mean by local is on your computer, and you are hosting the file (which I assume would be just for testing), then you need to connect the android device / emulator to the same local network as your computer and then access via the local ip of your computer.
And here is another question similar to this that has already been answered:
Load HTML file into WebView
I got a html file like this:
<body>
<h2>My html</h2>
<p> You could save #value per year.</p>
</body>
I load this page in android with a WebView
I got a stored value that I need to replace with #value , is this possible?
Update PagerAdapterClass where i need to use it :
#Override
public Object instantiateItem(ViewGroup container, final int position) {
WebView Content;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.view_pager_item, container,
false);
Content= (WebView) itemView.findViewById(R.id.iaps_url);
Content.loadUrl(myUrl.get(position));
((ViewPager) container).addView(itemView);
return itemView;
}
myUrl.get(position) reprezents the file location like "file:///android_asset/ScreenOne.html"
Yes.
First read the HTML from assets/raw to a String. And then use the replaceAll function of the string.
InputStream is = getAssets().open("webpage.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String page = new String(buffer);
page = page.replace("#value", "new string");
WebView webview = (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("", page, "text/html", "UTF-8", "");
Hi You can use the Android JavaScript Bridge technique. Look at below steps.
Steps 1. For enabling the Java script in a web view by default the JavaScript is disabled. You can enable through the WebSettings attached to your webview then enable the javascript with setJavaScriptEnabled()
For example
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
Steps 2. Building java script code to the android code
To bind the javascript and android code, it call addJavascriptInterface().passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.
For example, you can include the following class in your Android application:
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** call the stored value from java to javascript */
#JavascriptInterface
public integer getStoreValue() {
return 1;
}
}
You can bind this class to the JavaScript that runs in your WebView with addJavascriptInterface() and name the interface Android. For example:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
This creates an interface called Android for JavaScript running in the WebView. At this point, your web application has access to the WebAppInterface class. For example, here's some HTML and JavaScript that call the java stored value using the new interface when html widnow load: #see this link
<html>
<script type="text/javascript">
function getStoredValue() {
var output = document.getElementById('values');
output.innerHTML = Android.getStoreValue();
}
</script>
<body onload="getStoredValue()">
<h2>My html</h2>
<p> You could save <a id= 'values'>
</a> per year.</p>
</body>
</html>
Let me know if you have any doubt, thank you.
I have one query. Can I pass Value from my html page to My Activity file.
html file located in assets/www folder and Activity file located in src/package_name
You need to use JavaScriptInterface. In your web view add this Interface.
Make JavaScriptInterface class like (Here you can use any name for your class)
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context context) {
mContext = context;
}
/** Get passed value from the web page here */
public void showMyValue(String passedValue) {
android.util.Log.i("TAG", "I Got this value:" + passedValue);
}
}
Add this interface in your webview like
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
Now in your webpage, call this method to pass your value and do something need full with that value
<input type="button" value="ClickMe" onClick="passValueToAndroid('Hello Android!')" />
<script type="text/javascript">
function passValueToAndroid(yourPassingValue) {
Android.showMyValue(yourPassingValue);
}
</script>
Yes you can pass any variable from html to activity.
You need to create JavaScript Interface to interact between html to activity,
Refer this link for implementation detail
http://developer.android.com/guide/webapps/webview.html
I have defined some webview and I open some webpage on it
WebView wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("http://mypage.com/");
My question is how can I count the number of links in that webpage ?
my first idea was to parse the html code and to count the "href" string in that html, but this solution sound like a noob solution to me. Is there more intelligent way to do this ?
If you can edit the HTML I think you can do that with a simple javascript function that sends the count data back to Android. You can see an answer about that here
The function in Javascript to count links can be as simple as this:
<script type="text/javascript">
function countLinks()
{
var all_a = document.getElementsByTagName("a");
return all_a.length;
}
</script>
First declare a JavaScriptInterface in android code:
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Get number of links */
public void getNumOfLinks(int numOfLinks) {
// Use the count as you like
}
}
Then add this interface to your webview, when you call it:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
Finally in the HTML code get the number of links from DOM and pass it to the java code via the interface:
<script type="text/javascript">
Android.getNumOfLinks(document.getElementsByTagName("a").length)
</script>
hello i'm using this example http://lexandera.com/2009/01/extracting-html-from-a-webview/ to get the HTML from a webview. But i need to use it in my superclass and i dont know how to do this. I just can see the html on a AlertDialog but i cant use it. How can I return it to my main class as String?
final Context myApp = this;
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
#SuppressWarnings("unused")
public void showHTML(String html)
{
new AlertDialog.Builder(myApp)
.setTitle("HTML")
.setMessage(html)
.setPositiveButton(android.R.string.ok, null)
.setCancelable(false)
.create()
.show();
}
}
final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");
Do the Followings :
Setting up WebView
First add JavaScriptInterface to webView as follows. Here "Android" will be used later to call functions in JavaScriptInterface later.
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(this), "MyAndroid");
The JavaScriptInterface Class:
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
}
HTML File:
<html>
<head>
<script type="text/javascript">
function getValue()
{
var x=document.getElementById("content").innerHTML;
// alert(x);
MyAndroid.receiveValueFromJs(x);
}
</script>
</head>
<body>
<div id="content">
This is html content <hr/>
Other contents;
<input type="button" onclick="getValue()" value="Get Content" />
</div>
</body>
</html>
Calling Java Script Function
//this calls javascript function
webView.loadUrl("javascript:getValue()");
Adding Callback function in JavaScriptInterface for MyAndroid.receiveValueFromJs(val):
public void receiveValueFromJs(String str) {
Toast.makeText(mContext, "Received Value from JS: " + str,Toast.LENGTH_SHORT).show();
}
Here you have returned HTML in str variable.
You can see my blog : http://ganeshtiwaridotcomdotnp.blogspot.com/2011/10/calling-javascript-function-from.html
for details.
I found another solution : Is it possible to get the HTML code from WebView
Can't you just make a global variable, like
String globalHtml;
And then assign it in the showHTML method?
globalHtml = html;
You can delete the AlertDialog code if you don't need it.