I am new to Stack Exchange and Andorid development.
I am working on Android webview. I have the following code in my activity class.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView wv;
WebSettings ws;
try {
wv = (WebView) findViewById(R.id.webview);
ws = wv.getSettings();
ws.setJavaScriptCanOpenWindowsAutomatically(true);
ws.setJavaScriptEnabled(true);
wv.clearCache(true);
wv.loadUrl("http://<ip address>:<port>/<context>");
} catch (Exception e) {
e.printStackTrace();
}
}
in layout-main.xml:
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
in AndroidManifest.xml:
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".POCActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
In the url I have index.html with the following code:
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript">
alert("Start");
</script>
</head>
<body>
<p>Database 1</p>
<div id="test"></div>
</body>
</html>
Working Environment:
- Eclipse indigo
- Android SDK min version 10
- Build Target 2.3.3
But the android code is working only once i.e. when I create a new android project and run the same, I can see the javascript alert appearing. From next time the javascript alert is not displayed. Even is any text changes(Say I modified "Database 1" to "Database 2") in the html page is also not displayed.
I tried the following:
- Cleared appcache
- Uninstalled the application and then ran the project again
- Cleared
Please let me know what I am doing wrong here. Any help will be much appreciated.
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
Used these on my code and then my alert() worked pefectly
This is a very old question, but I recently encountered the same problem and would like to share the solution to anyone who come across this later.
You will need to assign a custom WebChromeClient to your WebView to handle the alert.
mWebView.webChromeClient = object : WebChromeClient() {
override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
val alertDialog = AlertDialog.Builder(context)
.setMessage(message)
.setPositiveButton("OK") { dialogInterface, _ ->
dialogInterface.dismiss()
result?.confirm()
}
.setOnCancelListener { result?.cancel() }
.setCancelable(true)
.create()
alertDialog.setCanceledOnTouchOutside(true)
alertDialog.show()
//Here AlertDialog is just an example. You can also simply show a Toast.
//But remember to call JsResult.confirm() or JsResult.cancel()
return true
}
}
You need to call either JsResult.confirm() or JsResult.cancel() to notify your WebView whether the user confirmed or canceled the alert dialog. Otherwise, the WebView would assume an alert dialog is still showing(blocking the UI) and won't allow a new one to be shown.
Related
EDIT: This bug is Webview overriding the default minimum font size.
In my example, Webview sets the minimum font-size to 8px somewhere. The solution is below :)
Android Webview rem units scale way to large.
All rem units appear 8 times too large and out of place in Android Webview.
The only rem tag that works correctly is font-size:30rem; for text. Everything else
seems to scale way to large. i.e. 100rem = 800px # 1.0px scale.
Strangely, after I pass 8.0px while scaling, the box starts to enlarge.
This example works on every browser that supports rem units except Webview.
Anyone have an idea?
Online Example: http://digitalknob.com/rem.html
JSFiddle Example: https://jsfiddle.net/aquawicket/71p49ag9/
Android Example: http://digitalknob.com/remTest.apk
I've tried mWebView.getSettings().setLoadWithOverviewMode(true);
I've tried mWebView.getSettings().setUseWideViewPort(true);
I've tried < meta name="viewport" content="width=device-width, user-scalable=no" /> and other variations.
I've tried loading a default user style sheet.
rem.html
<!DOCTYPE html>
<html style="font-size:1.0px;">
<head>
</head>
<body style="font-size:16em;">
<button style="position:absolute;width:100px;height:100px;font-size:60px;" onclick="ScaleDown()">-</button>
<button style="position:absolute;left:110px;width:100px;height:100px;font-size:60px;" onclick="ScaleUp()">+</button>
<a id="text" style="position:absolute;top:20px;left:220px;font-size:60px;">1.0px</a>
<!-- FIXME: rem units appear 8 times too large and out of place in Android Webview.
The only rem tag that works correctly is font-size:30rem;
This html file works as expexted on all other browsers. -->
<div style="position:absolute;top:115px;width:100rem;height:100rem;background-color:green;">
<a style="position:relative;top:30rem;left:16rem;font-size:30rem;">Scale</a>
</div>
<script>
var scale = window.devicePixelRatio;
Update_Scale();
function ScaleDown(){
scale -= 0.5;
Update_Scale();
}
function ScaleUp(){
scale += 0.5;
Update_Scale();
}
function Update_Scale(){
document.documentElement.style.fontSize = parseFloat(scale).toFixed(1)+"px";
document.getElementById("text").innerHTML = parseFloat(scale).toFixed(1)+"px";
}
</script>
</body>
</html>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="digitalknob.remTest"
android:installLocation="auto"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:targetSdkVersion="19" android:minSdkVersion="19"></uses-sdk>
<uses-permission android:name="android.permission.INTERNET"/>
<application android:label="remTest"
android:icon="#mipmap/icon"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<activity android:name="digitalknob.remTest.WebviewActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
WebviewActivity.java
package digitalknob.remTest;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebviewActivity extends Activity {
private WebView mWebView;
#Override protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
mWebView=(WebView)findViewById(R.id.webview_webview);
mWebView.setWebContentsDebuggingEnabled(true); //Debuggable in Chrome
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.loadUrl("http://digitalknob.com/rem.html");
}
#Override public void onBackPressed(){
System.exit(0);
}
}
webview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="#+id/webview_webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
I found that setting the following webview settings will act as a workaround for this bug.
mWebView.getSettings().setMinimumFontSize(1);
mWebView.getSettings().setMinimumLogicalFontSize(1);
setMinimumFontSize
These settings really should only be honored for actual text display, not rem based positioning/sizing. This must but an android webview bug.
I am facing a strange issue.
In my application, I need to load a static html file based on clicked button in a WebView from assets folder.
Now among 5 html files, one html file contains 15 static links. These links need to redirect user to the mentioned url in a mobile browser. I have used target="_blank" for that purpose as follows in my html file.
<div class="lid">Railway Reservation </div>
Now, this works fine in a sample application with a simple WebView without any WebViewClient added to it.
But I need a WebViewClient for my other functionalities. So at that time target="_blank" is totally ignored. And the url is opened in a WebView itself.
I found a workaround, that I can use shouldOverrideUrlLoading as follows:
myWebView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
if(url.equalsIgnoreCase("https://www.irctc.co.in/"))
{
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
else
return super.shouldOverrideUrlLoading(view, url);
}
});
So this is opening that particular url in a default browser.
So basically my questions are:
Why is target="_blank" ignored while we use WebViewClient? And is there any other workaround for this issue? Because I have 15 links, which I would need to compare. I can't load all urls in a new browser, as there are a few links, which need to be opened in a same WebView, too.
I have an idea for a workaround. Replace all links which should been opened in a new window with a custom schema. Then you can handle that by your own.
For a minimal interruption set also a custom theme and handle all configuration changes:
<activity android:name="com.example.LinkHandler"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="your.link.handler.schema"/>
</intent-filter>
</activity>
Then in your link handler you can read the url by using getIntent().getData().
Please also keep in mind that you should handle http and https, I skipped that in my short example above.
Here is an JavaScript example how to rewrite the urls:
for(var i=0; i<document.links.length; i++) {
if(document.links[i].target == "_blank") {
document.links[i].href = "your.schema.for."+document.links[i].href;
}
}
<ul>
<li>Test 1</li>
<li>Test 2</li>
<li>Test 3</li>
<li>Test 4</li>
</ul>
I'm trying to build a simple localStorage example using android webview. I'm having some trouble when i close the app. Everytime i start the app, values stored in localStorage disappear. I googled it and couldn't find a proper solution. Here I put my HTML, Java, Manifest code samples. Any help will be appreciated.
HTML :
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter()
{
if(typeof(Storage)!=="undefined")
{
if (localStorage.clickcount)
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
}
else
{
localStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>
</body>
</html>
JAVA:
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDatabasePath(this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath());
webView.loadUrl("http://www.example.com/sample.html");
setContentView(webView);
MANIFEST:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Permission lines are placed under tag but outside the tag
and here is the scenario:
-turn off the internet connection of the mobile device
-start the app
-open the page inside the webview
-tap the button several times
-close the app (close it inside the task manager)
-turn on the internet connection of the mobile device
-start the app
-open the page
-tap button several times and it counts from beginning
you can create different scenarios while trying. The main problem is how to set the webView to use localStorage properly?There is something that i'm missing about webview.(this error does not occur when you try it on the chrome browser or any other browser)
This seems like a bug of webview. I was actually trying to open 3 different pages inside a webview and I was loosing localStorage data. I splitted this activity into 3 activities that each of them opens only one page. And the problem disappeared.
I am building an App with api level 11. this is my Java Code
myWebView = (WebView) findViewById(R.id.webSitioPublico);
final ProgressBar Pbar;
Pbar = (ProgressBar) findViewById(R.id.progresoSitioPublico);
WebSettings webSettings = myWebView.getSettings();
webSettings.setPluginState(PluginState.ON);
webSettings.setPluginsEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setJavaScriptEnabled(true);
setExplorer(url);
My SWF is on my own external server
with just
<object width="215" height="140">
<param name="movie" value="http://192.168.0.198:5771/es/games/paint.swf">
<embed src="http://192.168.0.198:5771/es/games/paint.swf"
width="215" height="140">
</embed>
</object>
I am testing on a Nexus 7 4.2.2 api level 17, but building this app for api level 11.
Nothing appears on screen just a box with question marks on the place where SWF should be.
my manifest
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name="Rafael"
android:hardwareAccelerated = "true">
<activity
android:name="Principal"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:screenOrientation="portrait"
android:hardwareAccelerated = "true"
>
</activity>
<service android:name="ScannerService" ></service>
</application>
But you can still download apk from adobe
http://helpx.adobe.com/fr/flash-player/kb/archived-flash-player-versions.html
it will work in firefox mobile, the default browser (but not chrome mobile)
i have done it and it work on my galaxy nexus with android 4.2.2 :)
I guess it isen't possible anymore.
SWF require Adobe flash who has been deleted from Android
Adobe Removing Flash for Android From Google Play
use it myWebView.load(url) instead of setExplorer(url);
I'm trying to make an Android app with a webview in which I have an html page. This one contains a "div" tag with the contentEditable property set to true.
My problem: by launching the app, I can't edit the text.
I've been doing a lot of searches on Google but there was nothing on this topic. I was wondering if there was any permission missing (as the one to reach the net in the manifest) but I'm able to edit input and textarea tags (among others). I've refered to the WebView's API, WebViewClient, WebChromeClient but I didn't find any method which would configure a particular permission in order to do that.
Does the webview understand the contentEditable property? It's not working, even if the webview is supposed to interpret html.
My activity:
public class WebAppStackOverFlowActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.webView) ;
webView.setWebChromeClient (new WebChromeClient()) ;
webView.loadUrl("file:///android_asset/www/index.html") ;
}
}
My asset/www/index.html file:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name" value="this is an input tag" />
<br />
<div contenteditable="true">this is an editable div tag</div>
<br />
<textarea rows="" cols="">this is a textarea tag</textarea>
</body>
</html>
My main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
contentEditable is supported by the default browser on Android version 3.0 (Honeycomb) and up (source).
So, if you're running this on Gingerbread, that would explain why it's not working.