I am loading some urls in my app using android WebView and all successful. But when i am trying to load this url:
http://dev.infibond.com/cloud/instagram?user_profile=https%3A%2F%2Fscontent.cdninstagram.com%2Ft51.2885-19%2Fs150x150%2F13534190_829691380497090_1099495058_a.jpg&user_name=infibondtest
But for some reason i am failing - "view.loadUrl(url);" in "shouldOverrideUrlLoading" doesn't show the page and doesn't load another url. just shows a white page.
The response code from the server is 304.
Before i am getting to this url, i am doing authentication with Instagram and sending the access token as a cookie.
public class CloudWebViewActivity extends ActivityBase {
public static final String TAG = "WebViewActivity";
private static final String WEB_VIEW_TOKEN = "token";
private static final String WEB_VIEW_TITLE = "title";
private static final String WEB_VIEW_URL = "url";
private ProgressBar mPbProgress;
private Toolbar mToolbar;
private String mTitle, mUrl;
public static void setInstance(Context context, String title, String url) {
Intent starter = new Intent(context, CloudWebViewActivity.class);
starter.putExtra(WEB_VIEW_TITLE, title);
starter.putExtra(WEB_VIEW_URL, url);
context.startActivity(starter);
}
// MARK: Lifecycle
protected void onCreate(Bundle savedInstanceState) {
mTitle = getIntent().getStringExtra(WEB_VIEW_TITLE);
mUrl = getIntent().getStringExtra(WEB_VIEW_URL);
super.onCreate(savedInstanceState);
AppInstance.sharedInstance().getBus().register(this);
}
#Override
protected void onResume() {
super.onResume();
AppInstance.sharedInstance().setSelf();
mToolbar.setTitle(mTitle);
mPbProgress.setVisibility(View.VISIBLE);
}
#Override
protected void onDestroy() {
super.onDestroy();
AppInstance.sharedInstance().getBus().unregister(this);
}
#SuppressLint("SetJavaScriptEnabled")
public void findViews() {
setContentView(R.layout.webview_activity);
mPbProgress = (ProgressBar) findViewById(R.id.pBProgress);
final WebView mWebView = (WebView) findViewById(R.id.webView);
if (mWebView != null) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.setWebViewClient(webViewClient);
// Register a new JavaScript interface called HTMLOUT
mWebView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
}
if (JavaUtils.isNotNullNotEmptyNotWhiteSpaceOnly(mUrl) && mWebView != null) {
String cookieString = WEB_VIEW_TOKEN + "=" + NetworkManager.instance().getToken();
CookieManager.getInstance().setCookie(mUrl, cookieString);
mWebView.loadUrl(mUrl);
} else {
InfiLogger.getInstance().logRemoteException(new RuntimeException("Cloud service: " + mTitle + " came with an empty/null url address"));
AndroidUtils.showToast(R.string.error_cant_load_url);
}
}
#Override
public Toolbar setToolbar() {
mToolbar = (Toolbar) findViewById(R.id.mToolbar);
if (mToolbar != null) {
mToolbar.setVisibility(View.VISIBLE);
}
return mToolbar;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
private void handleProgressBarVisibility(String url) {
if (url.contains("login") ||
url.contains("https://api.twitter.com/oauth/authorize?oauth_token=") ||
url.contains("https://vimeo.com/log_in") ||
url.contains(".jpg")) {
mPbProgress.setVisibility(View.GONE);
} else {
mPbProgress.setVisibility(View.VISIBLE);
}
}
private final WebViewClient webViewClient = new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
handleProgressBarVisibility(url);
String cookieString = WEB_VIEW_TOKEN + "=" + NetworkManager.instance().getToken();
CookieManager.getInstance().setCookie(mUrl, cookieString);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
if (url.startsWith("http://dev.infibond.com/api/cloud/")) {
mPbProgress.setVisibility(View.GONE);
// This call inject JavaScript into the page which just finished loading.
view.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AndroidUtils.showToast(error.getDescription());
} else {
AndroidUtils.showToast(R.string.gen_Something_went_wrong);
}
mPbProgress.setVisibility(View.INVISIBLE);
}
};
// An instance of this class will be registered as a JavaScript interface
class MyJavaScriptInterface {
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(String html) {
// process the html as needed by the app
InfiLogger.d("infi", "html: " + html);
if (html.contains("code")) {
final boolean success;
if (html.contains("\"code\":200")) {
AndroidUtils.showToast(AndroidUtils.getString(R.string.cloud_sync_start) + mTitle);
success = true;
} else {
AndroidUtils.showToast(AndroidUtils.getString(R.string.gen_Something_went_wrong));
success = false;
}
AppInstance.sharedInstance().getBus().post(new CloudConnectionStateChangedBusEvent(mTitle, success));
finish();
}
}
}
}
I am not 100% sure, but it seems like you have a lot of small errors. I think the one in question is here:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
handleProgressBarVisibility(url);
String cookieString = WEB_VIEW_TOKEN + "=" +
NetworkManager.instance().getToken();
CookieManager.getInstance().setCookie(mUrl, cookieString);
view.loadUrl(url);
return true;
}
The view.loadUrl(url) seems very wrong to me. I think you may need to change this to something like:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("dev.infibond.com")) {
return false;
}
// otherwise, they are leaving the site, so open a new
// browser instead
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
And remove the guts of what you did here. Most of it is findViews() and should not be repeated anyway. I'm guessing this is what you meant to do with
handleProgressBarVisibility(url) in the WebViewClient but I'm not really sure:
#Override
public void onLoadResource(WebView view, String url) {
handleProgressBarVisibility(url);
}
Related
I have app's MainActivity like this, and this app can't download file with webview
Anybody knows how to fix the download problem?
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Webkit;
namespace REC
{
[Activity(Label = "APPNAME", MainLauncher = true, Icon = "#drawable/rec512", ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
public class MainActivity : Activity
{
private WebView mWebView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
RequestWindowFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Main);
mWebView = FindViewById<WebView>(Resource.Id.webview);
mWebView.Settings.SetRenderPriority(WebSettings.RenderPriority.High);
mWebView.Settings.JavaScriptEnabled = true;
mWebView.LoadUrl("http://www.APPname.com");
mWebView.SetWebViewClient(new WebViewClient());
// mWebView.SetDownloadListener(new MyDownloadListener()
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = (WebRequest)base.GetWebRequest(address);
// Perform any customizations on the request.
// This version of WebClient always preauthenticates.
request.PreAuthenticate = true;
return request;
}
class MonkeyWebChromeClient : WebChromeClient
{
public override bool OnJsAlert(WebView view, string url, string message, JsResult result)
{
return base.OnJsAlert(view, url, message, result);
}
public override Boolean OnJsConfirm(WebView view, String url, String message, JsResult result)
{
return base.OnJsConfirm(view, url, message, result);
}
public override Boolean OnJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result)
{
return base.OnJsPrompt(view, url, message, defaultValue, result);
}
}
public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back && mWebView.CanGoBack())
{
mWebView.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
}
public class WebClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
//return base.ShouldOverrideUrlLoading(view, url);
view.LoadUrl(url);
return true;
}
internal object GetWebRequest(Uri address)
{
throw new NotImplementedException();
}
}
}
You did not implement webview download listener,please refer to the following code :
public class MainActivity : Activity
{
WebView wv1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
wv1 = FindViewById<WebView>(Resource.Id.webView1);
wv1.SetDownloadListener(new MyDownloadListerner(this));
wv1.LoadUrl("https://notepad-plus-plus.org/download/v7.3.2.html");
}
class MyDownloadListerner : Java.Lang.Object, IDownloadListener
{
Context cont;
public MyDownloadListerner(Context context)
{
cont = context;
}
public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
{
Android.Net.Uri uri = Android.Net.Uri.Parse(url);
Intent intent = new Intent(Intent.ActionView,uri);
cont.StartActivity(intent);
}
}
}
Note: This method is start another browser to download, you can also create a new thread to download file at the OnDownloadStart function.
screen shot:
Please follow the following code
public class WebViewFragment extends KaROFragment {
private WebView mWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_webview, container, false);
try {
mWebView = (WebView) view.findViewById(R.id.webView);
mWebView.setWebViewClient(new myWebClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.loadUrl("https://www.google.com/");
} catch (Exception e) {
e.getStackTrace();
}
return view;
}
public class myWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
public void downloadAndPrintDocument(WebView webView, String title) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);
//noinspection deprecation
PrintDocumentAdapter printDocumentAdapter = webView.createPrintDocumentAdapter();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
printDocumentAdapter = webView.createPrintDocumentAdapter(title);
String documentName = title;
PrintJob printJob = printManager.print(documentName, printDocumentAdapter, new PrintAttributes.Builder().build());
List<PrintJob> printJobs = printManager.getPrintJobs();
printJobs.add(printJob);
} else {
// mContext.showToast(mContext.getString(R.string.mytools_printing_not_supported), 1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
the webpage have some popup ads is there any way to prevent the popup from loading when the popup loads the main site doesnt appears is there any way to load the main page with out popups and how can i add a download handler l mean the webview should support downloading .torrent file
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ProgressBar progressBar;
private LinearLayout layoutProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
layoutProgress = (LinearLayout) findViewById(R.id.layoutProgress);
webView.setVisibility(View.GONE);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
settings.setSupportZoom(true);
settings.setDisplayZoomControls(false);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
webView.setVisibility(View.VISIBLE);
layoutProgress.setVisibility(View.GONE);
progressBar.setIndeterminate(false);
super.onPageFinished(view, url);
}
public void but(View v){
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layoutProgress.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
super.onPageStarted(view, url, favicon);
}
});
if(isOnline()) {
webView.loadUrl("http://testsite.com/");
} else {
String summary = "<html><body><font color='red'>No Internet Connection</font></body></html>";
webView.loadData(summary, "text/html", null);
toast("No Internet Connection.");
}
}
private void toast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
public void but(View v){
webView.loadUrl("http://testsite.com/");
}
}
if the url changes then use shouldOverrideUrlLoading with some regex
so
List<String> validUrls = new LinkedList<>();
validUrls.add("https://www\\.google\\.com/*");
validUrls.add("https://www\\.facebook\\.com/*");
#Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (isValidUrl(url)) {
return false;
}
return true;
}
private boolean isValidUrl(String url) {
for (String validUrl : validUrls) {
Pattern pattern = Pattern.compile(validUrl, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
return true;
}
}
return false;
}
would match against any www.google.com or facebook.com urls
You can intercept the urls that are opened from the webview, I don't know if it would work with the popup:
WebViewClient client= new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if (url.equals("popupURL"){
return true;
}
return false;
}
}
webView.setWebViewClient(client);
I am Trying to implement the horizontal progressbar.But I am not understanding how to implement it in my class.Now I have implemented the dialog box which is in the format of sphener,But I want it in horizontal format showing progress of activity I am downloading some contents at that time it should show the progress.
My code is
public class Loginwebview extends Activity {
WebView webview;
String url1;
Bundle bundle=null;
private ProgressDialog progressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weblogin);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
bundle = new Bundle();
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
url1=url.toString();
bundle.putString("parameter", url1);
progressDialog = ProgressDialog.show(Loginwebview.this, "", "Loading...");
new Thread() {
public void run() {
try{
if(url1.contains("&mydownloads=true"))
{
if(url1.contains(".zip"))
{
sleep(150000);
Intent i1 = new Intent(Loginwebview.this, DownloadZipActivity.class);
i1.putExtras(bundle);
startActivityForResult(i1,0);
}
else
{
sleep(40000);
Intent i2 = new Intent(Loginwebview.this, DownloadOther.class);
i2.putExtras(bundle);
startActivityForResult(i2, 0);
}
}
else if(url1.contains("mydownloads=true"))
{
Log.d("its in Mydownloadssss",url1.toString());
Intent i3=new Intent(Loginwebview.this,Downloadlist.class);
i3.putExtras(bundle);
startActivityForResult(i3, 0);
}
}
catch(Exception e)
{
}
progressDialog.dismiss();
}
}.start();
return true;
}
public void onPageFinished(WebView view, String url1) {
Log.i("inside onpage", "Finished loading URL: " +url1);
String mainurl=url1;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e("onReceivedError", "Error: " + description);
}
});
webview.loadUrl("http://xxx/PublicModules/UserLoginVerify.aspx?userid=809&deviceid=DA0CE50D-0EEB-5E8E-9DCA-AED00F9BDFE5");
}
}
Hi i am new to android and i am doing a web application,here i have a webview i want to get the url address of each page so that i use webview.getUrl(); and i get the address of that page but i did not get the web address to the other pages,now find the url now how can i find the address of each page in android if necessary i can post my code.
package com.k.l;
import java.net.URL;
public class FregnhjActivity extends Activity implements OnTouchListener, Handler.Callback {
private static final int CLICK_ON_WEBVIEW = 1;
private static final int CLICK_ON_URL = 2;
private final Handler handler = new Handler(this);
private WebView webView;
private WebViewClient client;
Bundle link=new Bundle();
String idyoutube="";
String webUrl="";
String url="http://m.youtube.com/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView)findViewById(R.id.web);
webView.setOnTouchListener(this);
client = new WebViewClient(){
#Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
handler.sendEmptyMessage(CLICK_ON_URL);
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
webUrl = webView.getUrl();
System.out.println("###nasjkxbsa99999999"+webUrl);
super.onPageStarted(view, url, favicon);
}
};
webView.setWebViewClient(client);
webView.setVerticalScrollBarEnabled(false);
webView.loadUrl(url);
webView.getSettings().setJavaScriptEnabled(true);
}
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.web && event.getAction() == MotionEvent.ACTION_DOWN){
handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500);
}
return false;
}
public boolean handleMessage(Message msg) {
if (msg.what == CLICK_ON_URL){
handler.removeMessages(CLICK_ON_WEBVIEW);
return true;
}
if (msg.what == CLICK_ON_WEBVIEW){
Toast.makeText(this, "WebView clicked", Toast.LENGTH_SHORT).show();
webUrl = webView.getUrl();
System.out.println("sammmmm"+webUrl);
int start=webUrl.indexOf('?');
int end=webUrl.indexOf('v');
String yutube=webUrl.substring(start-1,end+1);
int ids=webUrl.indexOf('=');
idyoutube=webUrl.substring(ids+1);
return true;
}
return false;
}
}
i use on page finish methord it only load the address of the firstpage the next page after that is not shown
WebView webView webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("https://www.google.co.in/");
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i("shouldOverrideUrlLoading", url);
return super.shouldOverrideUrlLoading(view, url);
}
});
Try it..hope ths will help u..
I want to get a return value from Javascript in Android. I can do it with the iPhone, but I can't with Android. I used loadUrl, but it returned void instead of an object. Can anybody help me?
Same as Keith but shorter answer
webView.addJavascriptInterface(this, "android");
webView.loadUrl("javascript:android.onData(functionThatReturnsSomething)");
And implement the function
#JavascriptInterface
public void onData(String value) {
//.. do something with the data
}
Don't forget to remove the onData from proguard list (if you have enabled proguard)
Here's a hack on how you can accomplish it:
Add this Client to your WebView:
final class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d("LogTag", message);
result.confirm();
return true;
}
}
Now in your javascript call do:
webView.loadUrl("javascript:alert(functionThatReturnsSomething)");
Now in the onJsAlert call "message" will contain the returned value.
Use addJavascriptInterface() to add a Java object to the Javascript environment. Have your Javascript call a method on that Java object to supply its "return value".
Here's what I came up with today. It's thread-safe, reasonably efficient, and allows for synchronous Javascript execution from Java for an Android WebView.
Works in Android 2.2 and up. (Requires commons-lang because I need my code snippets passed to eval() as a Javascript string. You could remove this dependency by wrapping the code not in quotation marks, but in function(){})
First, add this to your Javascript file:
function evalJsForAndroid(evalJs_index, jsString) {
var evalJs_result = "";
try {
evalJs_result = ""+eval(jsString);
} catch (e) {
console.log(e);
}
androidInterface.processReturnValue(evalJs_index, evalJs_result);
}
Then, add this to your Android activity:
private Handler handler = new Handler();
private final AtomicInteger evalJsIndex = new AtomicInteger(0);
private final Map<Integer, String> jsReturnValues = new HashMap<Integer, String>();
private final Object jsReturnValueLock = new Object();
private WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = (WebView) findViewById(R.id.webView);
webView.addJavascriptInterface(new MyJavascriptInterface(this), "androidInterface");
}
public String evalJs(final String js) {
final int index = evalJsIndex.incrementAndGet();
handler.post(new Runnable() {
public void run() {
webView.loadUrl("javascript:evalJsForAndroid(" + index + ", " +
"\"" + StringEscapeUtils.escapeEcmaScript(js) + "\")");
}
});
return waitForJsReturnValue(index, 10000);
}
private String waitForJsReturnValue(int index, int waitMs) {
long start = System.currentTimeMillis();
while (true) {
long elapsed = System.currentTimeMillis() - start;
if (elapsed > waitMs)
break;
synchronized (jsReturnValueLock) {
String value = jsReturnValues.remove(index);
if (value != null)
return value;
long toWait = waitMs - (System.currentTimeMillis() - start);
if (toWait > 0)
try {
jsReturnValueLock.wait(toWait);
} catch (InterruptedException e) {
break;
}
else
break;
}
}
Log.e("MyActivity", "Giving up; waited " + (waitMs/1000) + "sec for return value " + index);
return "";
}
private void processJsReturnValue(int index, String value) {
synchronized (jsReturnValueLock) {
jsReturnValues.put(index, value);
jsReturnValueLock.notifyAll();
}
}
private static class MyJavascriptInterface {
private MyActivity activity;
public MyJavascriptInterface(MyActivity activity) {
this.activity = activity;
}
// this annotation is required in Jelly Bean and later:
#JavascriptInterface
public void processReturnValue(int index, String value) {
activity.processJsReturnValue(index, value);
}
}
On API 19+, the best way to do this is to call evaluateJavascript on your WebView:
webView.evaluateJavascript("foo.bar()", new ValueCallback<String>() {
#Override public void onReceiveValue(String value) {
// value is the result returned by the Javascript as JSON
}
});
Related answer with more detail: https://stackoverflow.com/a/20377857
The solution that #Felix Khazin suggested works, but there is one key point missing.
The javascript call should be made after the web page in the WebView is loaded. Add this WebViewClient to the WebView, along with the WebChromeClient.
Full Example:
#Override
public void onCreate(Bundle savedInstanceState) {
...
WebView webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
webView.setWebChromeClient(new MyWebChromeClient());
webView.loadUrl("http://example.com");
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished (WebView view, String url){
view.loadUrl("javascript:alert(functionThatReturnsSomething())");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
}
private class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d("LogTag", message);
result.confirm();
return true;
}
}
As an alternative variant that uses a custom scheme to communicate Android native code <-> HTML/JS code. for example MRAID uses this technic[About]
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
final WebView webview = new CustomWebView(this);
setContentView(webview);
webview.loadUrl("file:///android_asset/customPage.html");
webview.postDelayed(new Runnable() {
#Override
public void run() {
//Android -> JS
webview.loadUrl("javascript:showToast()");
}
}, 1000);
}
}
CustomWebView
public class CustomWebView extends WebView {
public CustomWebView(Context context) {
super(context);
setup();
}
#SuppressLint("SetJavaScriptEnabled")
private void setup() {
setWebViewClient(new AdWebViewClient());
getSettings().setJavaScriptEnabled(true);
}
private class AdWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("customschema://")) {
//parse uri
Toast.makeText(CustomWebView.this.getContext(), "event was received", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
}
}
customPage.html (located in the assets folded)
<!DOCTYPE html>
<html>
<head>
<title>JavaScript View</title>
<script type="text/javascript">
<!--JS -> Android-->
function showToast() {
window.location = "customschema://goto/";
}
</script>
</head>
<body>
</body>
</html>
You can do it like this:
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
public WebView web_view;
public static TextView textView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.ClearFlags(WindowManagerFlags.ForceNotFullscreen);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.main);
web_view = FindViewById<WebView>(Resource.Id.webView);
textView = FindViewById<TextView>(Resource.Id.textView);
web_view.Settings.JavaScriptEnabled = true;
web_view.SetWebViewClient(new SMOSWebViewClient());
web_view.LoadUrl("https://stns.egyptair.com");
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public class SMOSWebViewClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
{
view.LoadUrl(request.Url.ToString());
return false;
}
public override void OnPageFinished(WebView view, string url)
{
view.EvaluateJavascript("document.getElementsByClassName('notf')[0].innerHTML;", new JavascriptResult());
}
}
public class JavascriptResult : Java.Lang.Object, IValueCallback
{
public string Result;
public void OnReceiveValue(Java.Lang.Object result)
{
string json = ((Java.Lang.String)result).ToString();
Result = json;
MainActivity.textView.Text = Result.Replace("\"", string.Empty);
}
}