open inside and outside of webview - webview

can you please tell me whats wrong here? i want open my website and facebook (Facebook logging plugin) in webview only. all other external link will open in other external browsers. below code allow facebook to open in external browser.
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (!url.contains ("https://kroybook.com/')'https://facebook.com/")
{
Uri uri = Uri.parse(url);
startActivity(Intent.createChooser(new Intent(Intent.ACTION_VIEW, uri), "Choose browser"));
CookieManager.getInstance().setAcceptCookie(true);
} else {
myWebView.loadUrl(url);
return true;
}
return false;
}

This the code i used
public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null && url.startsWith("whatsapp://")) { view.getContext().startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } else { return false; } }

Related

Xamarin.Android webview does not open the file, but file upload works fine (need C# code)

I have WebView which works fine for file upload but when I click on files to open or download, nothing happens. but in normal browser when I click on file it is opened successfully. the intention of code is to open the file when it is clicked. file choose chrome extension is fine. I think there is need to add some code in WebViewListner block.
The activity code is here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Net;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace smartbookapp
{
[Activity(Label = "JobActivity")]
public class JobActivity : Activity
{
public WebView webview;
public IValueCallback mUploadMessage;
public static ProgressBar progressBar;
public static int FILECHOOSER_RESULTCODE = 1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Jobs);
webview = FindViewById<WebView>(Resource.Id.JobView);
// show progress bar
progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
//
webview.Settings.JavaScriptEnabled = true;
webview.Settings.SetAppCacheEnabled(true);
webview.Settings.AllowFileAccess = true;
webview.Settings.BuiltInZoomControls = true;
webview.SetWebViewClient(new WebViewListener());
webview.SetWebChromeClient(new JobWebChromeClient(this));
webview.LoadUrl("https://smartbook.pk/Jobs/index");
//
}
//
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Android.Net.Uri[] result = data == null || resultCode != Result.Ok ? null : new Android.Net.Uri[] { data.Data };
try
{
mUploadMessage.OnReceiveValue(result);
}
#pragma warning disable CS0168 // Variable is declared but never used
catch (Exception e)
#pragma warning restore CS0168 // Variable is declared but never used
{
}
mUploadMessage = null;
}
base.OnActivityResult(requestCode, resultCode, data);
}
// webview listener code here
public class WebViewListener : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
{
view.LoadUrl(request.Url.ToString());
return true;
}
public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
{
progressBar.Progress = view.Progress;
}
public override void OnLoadResource(WebView view, string url)
{
progressBar.Progress = view.Progress;
}
public override void OnPageFinished(WebView view, string url)
{
progressBar.Progress = 0;
}
}
public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back && webview.CanGoBack())
{
webview.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
}
// download files from webview
public class JobWebChromeClient : WebChromeClient
{
JobActivity WebViewActivity;
public JobWebChromeClient(JobActivity activity)
{
WebViewActivity = activity;
}
public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
{
WebViewActivity.mUploadMessage = filePathCallback;
Intent i = new Intent(Intent.ActionGetContent);
i.AddCategory(Intent.CategoryOpenable);
i.SetType("*/*");
WebViewActivity.StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), JobActivity.FILECHOOSER_RESULTCODE);
return true;
}
}
}
First of all, make sure your WebView has enabled javascript and the WebViewClient is set correctly.
WebView mWebview = FindViewById<WebView>(Resource.Id.webView1);
mWebview.Download += MWebview_Download;
var client = new WebViewClient();
mWebview.Settings.JavaScriptEnabled = true;
mWebview.SetWebViewClient(client);
mWebview.LoadUrl("your url");
Then, we shouldd achieve WebView.Download event(use DownloadManager to download the file)
private void MWebview_Download(object sender, DownloadEventArgs e)
{
var url = e.Url;
DownloadManager.Request request = new
DownloadManager.Request(Uri.Parse(url));
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted); //Notify client once download is completed!
request.SetDestinationInExternalPublicDir(Environment.DirectoryDownloads, "CPPPrimer");
DownloadManager dm = (DownloadManager)GetSystemService("download");
dm.Enqueue(request);
Toast.MakeText(ApplicationContext, "Downloading File",ToastLength.Long//To notify the Client that the file is being downloaded
).Show();
}

Do not ask login for rememberMe users in checkout process etc. in SAP Hybris

When I make rememberMe(spring security) active in Hybris, I want rememberMe users to behave like Hard Login users. I mean, I would like those rememberMe users (soft login) to not face any obstacle like when they want to proceed in the checkout process or something like that. How can I achieve this in SAP Hybris platform?
Your question: How to disable HardLogin for the remember-me user in Hybris?
find the detail explanation here
Change RequireHardLoginBeforeControllerHandler
Change beforeController method of RequireHardLoginBeforeControllerHandler.java, so that it always check if remember-me cookies present in the request and guid is missing or invalidated then create new guid without redirecting login page.
Below yourstorefrontRememberMe needs to change with your storefront name, like mySiteRemmberMe
public static final String SECURE_REMEMBER_ME_COOKIES = "yourstorefrontRememberMe";
#Resource(name = "guidCookieStrategy")
private GUIDCookieStrategy guidCookieStrategy;
#Override
public boolean beforeController(final HttpServletRequest request, final HttpServletResponse response,
final HandlerMethod handler) throws Exception
{
boolean redirect = true;
// We only care if the request is secure
if (request.isSecure())
{
// Check if the handler has our annotation
final RequireHardLogIn annotation = findAnnotation(handler, RequireHardLogIn.class);
if (annotation != null)
{
final String guid = (String) request.getSession().getAttribute(SECURE_GUID_SESSION_KEY);
if ((!getUserService().isAnonymousUser(getUserService().getCurrentUser()) || checkForAnonymousCheckout()) &&
checkForGUIDCookie(request, response, guid))
{
redirect = false;
}
if (redirect)
{
if(isRememberMeCookiePresent(request))
{
// If you find your guid is missing, lets recreate it.
guidCookieStrategy.setCookie(request, response);
return true;
}
else
{
LOG.warn((guid == null ? "missing secure token in session" : "no matching guid cookie") + ", redirecting");
getRedirectStrategy().sendRedirect(request, response, getRedirectUrl(request));
return false;
}
}
}
}
return true;
}
protected boolean isRememberMeCookiePresent(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if ((cookies == null) || (cookies.length == 0)) {
return false;
}
for (Cookie cookie : cookies) {
if (SECURE_REMEMBER_ME_COOKIES.equals(cookie.getName())) {
return cookie.getValue() != null;
}
}
return false;
}

Visit Last Loaded URL

I'm making an app in Xamarin android where user navigates. The app contains webview. When a user opens webview, url gets loaded and browsing can be done. When he ends the app and opens it again, URL is loaded again instead of viewing last visited URL.
I don't know what I'm doing wrong here.
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.SetWebViewClient(new MyWebClient());
CookieManager.Instance.SetAcceptCookie(true);
webView.Settings.JavaScriptEnabled = true;
webView.Settings.SetAppCacheEnabled(true);
webView.LoadUrl(getUrl());
webView.SetPadding(0, 0, 0, 0);
webView.Settings.SetSupportZoom(true);
}
public void saveUrl(String url)
{
ISharedPreferences sp = GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
ISharedPreferencesEditor editor = sp.Edit();
editor.PutString("SAVED_URL", url);
editor.Commit();
}
public String getUrl()
{
ISharedPreferences sp = GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
//If you haven't saved the url before, the default value will be google's page
return sp.GetString("SAVED_URL", "http://google.com");
}
public void onPageFinished(WebView view, String url)
{
this.onPageFinished(view, url);
saveUrl(url);
}
}
internal class MyWebClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return false;
}
}
You have placed onPageFinished method in an Activity. It should be overridden in MyWebClient class as below:
internal class MyWebClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return false;
}
public override void OnPageFinished(WebView view, String url)
{
base.OnPageFinished(view, url);
//Save the url here.
//This method itself gives you the last url loaded as it's url Parameter.
ISharedPreferences sp = Application.Context.GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
ISharedPreferencesEditor editor = sp.Edit();
editor.PutString("SAVED_URL", url);
editor.Commit().
}
}
This method will be automatically called when URL finished loading and then you will store your loaded URL in this method.

open ads in external browser in webview android

I created app with webview, and i want load all internal links in webview and load external links in android browser. Now problem is I am using html ads and when i click on ads i want open external browser, but its opening in webview. only problem with ads otherwise everything is works fine. So how can i do this?
My code is below:
`class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().equals("www.mysite.com")) {
view.loadUrl(url);
return true;
}else{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;}}`
You code should be:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.mysite.com")) {
return true;
}else{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return false;
}
}
All I changed was:
1.) Returning true loads the URL in the webview, no need for view.loadUrl()
2.) Return false when you broadcast the ACTION_VIEW intent
I did the some modifications and it is working perfectly for banner ads.
I have made following changes:
changed if condition.
I am returning false for 'if' block as documentation says:
If WebViewClient is provided, return true means the host application
handles the url, while return false means the current WebView handles
the url
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (url.contains("www.mysite.com"))
{
view.loadUrl(url);
return false;
}else
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}

Launching the application from an url in the browser for BlackBerry?

I am developing one application where i will launch a url in the browser from which i will launch my application.
Suppose if i will click google.com, and press enter, it will launch my application. For that i tried with the HttpFilterRegistry API.
For reference i am using the HTTPFilterDemo application. But currently while launching the app, i am getting the NullPointerException.
I wrote the below code i the openFilter Method:
public Connection openFilter(String name, int mode, boolean timeouts) throws IOException {
Logger.out("Protocol", "it is inside the openFilter method");
_url = name.substring(2);
_requestHeaders = new HttpHeaders();
_responseHeaders = new HttpHeaders();
_responseHeaders.setProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, "text/html");
Logger.out("Protocol", "here it is come ::::44444444");
final int modHandle = CodeModuleManager.getModuleHandle("AppLaunchBrowser");
Logger.out("Protocol", "here is the module handle:::" + modHandle);
final ApplicationDescriptor[] apDes = CodeModuleManager.getApplicationDescriptors(modHandle);
final ApplicationDescriptor appDescriptor = new ApplicationDescriptor(apDes[0], new String[] {});
Logger.out("Protocol", "here is the app descriptor:::" + appDescriptor);
try {
final int appCode = ApplicationManager.getApplicationManager().runApplication(appDescriptor, true);
Logger.out("Protocol", "here is the app code:::" + appCode);
} catch (ApplicationManagerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
return this;
}
And in the application class i am creating alternative entry point and using like below:
public class AppLaunch extends UiApplication{
public static void main(String args[])
{
Logger.out("AppLaunch", args+"length of the arguments::::" +args.length);
if((args != null) && (args.length > 0) && (args[0].equals("background")))
{
Logger.out("AppLaunch", "in the alternate entry point");
// Logger.out("AppLaunch", args+"length of the arguments::::" +args.length);
HttpFilterRegistry.registerFilter("www.google.co.in", "com.innominds.ca", false);
}
else
{
Logger.out("AppLaunch", "Inside the Applaunch");
AppLaunch theApp = new AppLaunch();
theApp.requestForeground();
Logger.out("AppLaunch", "created the app launch object");
theApp.enterEventDispatcher();
// Logger.out("AppLaunch", "in the alternate entry point");
// HttpFilterRegistry.registerFilter("www.google.co.in", "com.innominds.ca", false);
}
}
public AppLaunch()
{
checkPermissions();
showTestScreen();
}
private void checkPermissions()
{
ApplicationPermissionsManager apm = ApplicationPermissionsManager.getInstance();
ApplicationPermissions original = apm.getApplicationPermissions();
if(original.getPermission(ApplicationPermissions.PERMISSION_BROWSER_FILTER) == ApplicationPermissions.VALUE_ALLOW)
{
// All of the necessary permissions are currently available
return;
}
ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_BROWSER_FILTER);
boolean acceptance = ApplicationPermissionsManager.getInstance().invokePermissionsRequest(permRequest);
if(acceptance)
{
// User has accepted all of the permissions
return;
}
else
{
}
}
private void showTestScreen()
{
UiApplication.getUiApplication().pushScreen(new AppLaunchScreen());
}
}
Finally i was able to resolve this issue. Actually NPE is coming in some other callback methods because i was implementing the FilterBaseInterface.

Resources