javascript alert message not working in android application - javascript

I have created an android application with simple webview function. In my html page which webview loads, I am using following script.
var message="!!YOU CANNOT COPY ANY TEXT OR IMAGE FROM THIS APP!";
function clickIE4()
{
if (event.button==2)
{
alert(message);
return false;
}
}
function clickNS4(e)
{
if (document.layers||document.getElementById&&!document.all)
{
if (e.which==2||e.which==3)
{
alert(message);
return false;
}
}
}
if (document.layers)
{
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById)
{
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false")
//for disable select option
//document.onselectstart = new Function("alert(message);return false");
When I open this in android webview application, it does not show the alert message. It works fine when I open it in normal browser.

You need to create WebChromeClient and set to WebiView. Also override onJsAlert method.
WebChromeClient webChromeClient = new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(context)
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.create()
.show();
return true;
}
}
webView.setWebChromeClient(webChromeClient);

Related

Android webview fullscreen video

I working on host a website that include videos , when I run the video and click to fullscreen player button the white color fill all screen but the video sound still playing
MainActivity.class
mWebview = (WebView) findViewById(R.id.web);
mWebview.setWebViewClient(new MyWebViewClient());
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
mWebview.getSettings().setDomStorageEnabled(true);
mWebview.loadUrl("http://www.my-site.com/");
mWebview.setWebChromeClient(new WebChromeClient() {
public void onShowCustomView (View view, WebChromeClient.CustomViewCallback callback) {
//do stuff
}
public void onHideCustomView () {
//do stuff
}
});
MyWebViewClient.class
public class MyWebViewClient extends WebViewClient {
public boolean shuldOverrideKeyEvent(WebView view, KeyEvent event) {
return true;
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try {
String s = Uri.parse(url).getHost();
if((s.contains("rulanerder"))|| (s.contains("disqus"))){
view.stopLoading();
view.goBack();
return true; }
}
// reject anything other
} catch (Exception e) {
Log.d("Error", "shouldOverrideUrlLoading");
}
return false;
}
}
how can fixed that ?

JavascriptInterface function crashing javascript on web page

I have a webview in my android app. I want to show a banner only if the web page is viewed on browser. I created an interface and it tests fine but because the web page doesn't recognize the function the other javascript on the page doesn't load. Here is my Code:
Interface Class
import android.content.Context;
import android.webkit.JavascriptInterface;
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public Boolean getUser() {
return true;
}
}
Activity Class
public class MainActivity extends Activity {
ProgressBar progressBar;
WebView webview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.webview);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
webview.addJavascriptInterface(new WebAppInterface(this),"Android");
this.webview.getSettings().setUserAgentString(
this.webview.getSettings().getUserAgentString()
+ " "
+ getString(R.string.user_agent_suffix)
);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if (progress == 100) {
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.VISIBLE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webview.loadUrl("http://www.getonfleek.com");
ParsePush.subscribeInBackground("test");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
}
}
HTML
</script>
<script type="text/javascript">
$(document).ready(function(){
var user = Android.getUser();
if(user == null){
//do something on web
}else{
//do something in app
}
});
</script>
Check to make sure the interface exists before trying to call it.
<script type="text/javascript">
$(document).ready(function(){
var user = null;
if(typeof Android !== 'undefined'){
user = Android.getUser();
//do something in app
}else{
//do something on web
}
});
</script>

How to alert the user if his internet connection is down

I'm developing an android app using HTML & JS, (will use PhoneGap after successful development) and I want the app to alert the user if his device is not connected to WiFi or Mobile data, and the app should close after the alert.
I tried this for reference:
How to alert the user when there's no internet connection
However, it doesn't seem to work for me.. Please suggest some other alternative for the same.
Sorry because I don't have enough repulation to comment.
To close the app, you could use:
navigator.app.exitApp();
public void onCreate(Bundle obj)
{
super.onCreate(obj)
setContextView(layout);
if (isOnline())
//do your task
else
{
try {
AlertDialog alertDialog = new AlertDialog.Builder(con).create();
alertDialog.setTitle("Info");
alertDialog.setMessage("Internet not available,try again later.");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
}
catch(Exception e)
{
Log.d(Constants.TAG, "Show Dialog: "+e.getMessage());
}
}
}

Call javascript method on alert button click

I have to call a javascript method on OK clicked from an alert created in java plugin. Actually the alert is displayed on click of the notification from the status bar.
// Method to collect info from pending intent on notification click
public void launchNotification()
{
Intent intent = getIntent();
if(intent!=null)
{
if(intent.getExtras().getBoolean("fromNotification"))
{
final String notificationType = intent.getStringExtra("notificationType");
final String twoWeeksNotificationType = intent.getStringExtra("2WeeksNotificationType");
final String tasksNotificationType = intent.getStringExtra("tasksNotificationType");
if(notificationType != null || twoWeeksNotificationType != null || tasksNotificationType != null)
{
if(notificationType != null && notificationType.equals("dailyReviewAvailable"))
{
NotificationManager nMgr = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancel("DailyReview", 0);
Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
public void run() {
showAlertForNotifications(notificationType);
}
}, 1000L);
}
intent.putExtra("fromNotification",false);
}
else
finish();
}
}
// Method for launching alert after notification is clickedpublic void
showAlertForNotifications(String notificationIdStr) {
if(notificationIdStr.equals("dailyReviewAvailable")) {
Log.d("Notification", "Daily Review Start");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Actions Hero");
adb.setMessage("Would you like to send your daily review?");
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
showDailyReview();
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Cancel' Button
dialog.cancel();
finish();
}
});
//adb.setIcon(R.drawable.icon);
adb.show();
}
else {
//do later
}
}
// Method to call javascript function on OK click of alert button in java
public void showDailyReview() {
Log.v("showDailyReview", "Before");
// This javascript function cannot be invoked super.sendJavascript("javascript:app.runningDailyReview('DailyReview')");
Log.v("showDailyReview", "After");
finish();
}
How should I invoke the javascript method on clicking OK on the alert shown ??
Thanks..

Inject JavaScript in Android after WebView has finished loading from a previous JavaScript Injection

I have a Webview, that onPageFinished injects some JavaScript, this JavaScript populates the form on this page and submits the form successfully.
My question is how do i then check for onPageFinished of the page the WebView goes to after the form has been submitted? As i wish to inject some more JavaScript to pull out some values.
Thanks in advance.
You need to manage yourself redirection through a flag that you manipulate in all 3 relevant methods:
boolean loadingFinished = true;
boolean redirect = false;
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
view.loadUrl(urlNewString);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap facIcon) {
loadingFinished = false;
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
#Override
public void onPageFinished(WebView view, String url) {
if(!redirect){
loadingFinished = true;
}
if(loadingFinished && !redirect){
//HIDE LOADING IT HAS FINISHED
} else{
redirect = false;
}
}
});

Categories