I am developing an android application. It is a WebView for my website. The website contains a popup button, on clicking it, a new window will open and display the content. The link can be from external site. However when I implemented this, the new tab is opening and just after that it popsup to open browser inspite of opening it in webview. I tried with same website link also. For both case it popsup browser. Please help me with a working code to open a new tab and close it programatically. Here is my code:
public class MainActivity extends Activity {
private WebView webView;
private myWebChromeClient mWebChromeClient;
private myWebViewClient mWebViewClient;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
mWebViewClient = new myWebViewClient();
webView.setWebViewClient(mWebViewClient);
WebSettings webSettings = webView.getSettings();
mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webView.getSettings().setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
String aapp = "Mozilla/5.0 (Linux; Android 6.0.1; Redmi Note 3 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36";
webSettings.setUserAgentString(aapp);
webView.loadUrl("http://website/test.php");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();
finish();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
class myWebChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
WebView newWebView = new WebView(MainActivity.this);
WebSettings webSettings = newWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
String app = "Mozilla/5.0 (Linux; Android 6.0.1; Redmi Note 3 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36";
webSettings.setUserAgentString(app);
// Other configuration comes here, such as setting the WebViewClient
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(newWebView);
dialog.show();
newWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onCloseWindow(WebView window) {
dialog.dismiss();
}
});
((WebView.WebViewTransport)resultMsg.obj).setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
}
class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView webView, String url) {
String webUrl = webView.getUrl();
System.out.println(webUrl);
super.onPageFinished(webView, url);
}
}
}
When a link is touched inside a webpage then depending on a webpage implementation there are two possible scenarios:
1) The link will be opened in the same window.
2) The link will be opened in new window.
For 1st scenario using below code:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
Overiding shouldOverrideUrlLoading inside WebViewClient implementation will open link in same window.
For 2nd case, where webpage is requesting a url to be open in new window. For this case we need this:
webView.getSettings().setSupportMultipleWindows(true);
and then adding a new web chrome client to webview to get the event when a new window is requested by webpage
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
WebView newWebView = new WebView(WebpageActivity.this);
newWebView.getSettings().setJavaScriptEnabled(true);
newWebView.getSettings().setSupportZoom(true);
newWebView.getSettings().setBuiltInZoomControls(true);
newWebView.getSettings().setPluginState(PluginState.ON);
newWebView.getSettings().setSupportMultipleWindows(true);
view.addView(newWebView);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
newWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
return true;
}
}
});
Happy to help.
Related
Is android webview able to display mp4 video with video tag?
In my application, my webview need to display video in . But, my webview is displays only blackscreen(audio is working fine).
I`m working in Android API Level 29.
This is my code about settings of webview
mWebSettings = mWebView.getSettings();
mWebSettings.setJavaScriptEnabled(true);
mWebSettings.setSupportMultipleWindows(true);
mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
mWebSettings.setLoadWithOverviewMode(true);
mWebSettings.setUseWideViewPort(true);
mWebSettings.setSupportZoom(true);
mWebSettings.setBuiltInZoomControls(true);
mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebSettings.setDomStorageEnabled(true);
mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
mWebSettings.setMediaPlaybackRequiresUserGesture(false);
mWebSettings.setPluginState(WebSettings.PluginState.ON);
mWebSettings.setAllowUniversalAccessFromFileURLs(true);
mWebSettings.setAllowFileAccessFromFileURLs(true);
mWebSettings.setAllowFileAccess(true);
mWebSettings.setUserAgentString("Mozilla/5.0 (Linux; Android 10; SM-A205U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.185 Mobile Safari/537.36");
mWebView.setBackgroundColor(0x00000000);
mWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
mWebView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.loadUrl(request.getUrl().toString());
}
return super.shouldOverrideUrlLoading(view, request);
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
#SuppressLint("SetJavaScriptEnabled")
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
// Dialog Create Code
WebView newWebView = new WebView(MainActivity.this);
WebSettings webSettings = newWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
newWebView.setVisibility(View.GONE);
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(newWebView);
ViewGroup.LayoutParams params = dialog.getWindow().getAttributes();
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = ViewGroup.LayoutParams.MATCH_PARENT;
dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
//dialog.show();
newWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onCloseWindow(WebView window) {
dialog.dismiss();
}
});
// WebView Popup에서 내용이 안보이고 빈 화면만 보여 아래 코드 추가
newWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mWebView.loadUrl(view.getUrl());
}
});
((WebView.WebViewTransport) resultMsg.obj).setWebView(newWebView);
resultMsg.sendToTarget();
//Log.d(MainURL,newWebView.getUrl());
return true;
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onCloseWindow(WebView window) {
super.onCloseWindow(window);
window.goBack();
}
});
And I use mWebView.loadUrl(url) to load my url.
mWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
This line is the cause of your problem. Video playback will not work when layer type is software. So change it either to LAYER_TYPE_NONE or LAYER_TYPE_HARDWARE like:
mWebView.setLayerType(WebView.LAYER_TYPE_HARDWARE , null);
or
mWebView.setLayerType(WebView.LAYER_TYPE_NONE, null);
Quick tip: Search more on internet regarding differences between various layer types and their performance and other aspects and then only use them wisely.
When I am trying to load a Magento 2 e-commerce website in android WebView, i'm getting following error message:
"Unable to send the cookie. Maximum number of cookies would be
exceeded."
What's the cause of this error.? How can I fix this.?
Could anyone help me.?
Android Code
WebView webView=(WebView) findViewById(R.id.disp);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowFileAccess(true);
webView.setWebViewClient(new MyViewClient());
try {
webView.loadUrl("https://sweetroomksa.com/");
}catch (Exception e){
}
Create your custom WebViewClient class and then try to load WebView url like below:
WebViewClientImpl.java
public class WebViewClientImpl extends WebViewClient {
private Activity activity = null;
public WebViewClientImpl(Activity activity) {
this.activity = activity;
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if(url.indexOf("/sweetroomksa.com/") > -1 )
return false;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebViewClientImpl webViewClient = new WebViewClientImpl(this);
webView.setWebViewClient(webViewClient);
webView.loadUrl("https://sweetroomksa.com/");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
this.webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Above code working perfectly in my device.
Hope above answer may help you.
I have a webview app and facing a problem that
when I click on Hyperlink then it opens in default browser.
But I want to open that link in same webview.
How to open it in same webview.
Here is my code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.myWebView);
myWebView.loadUrl("file:///android_asset/abc/index.html");
myWebView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("file:///android_asset/abc/index.html")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
Do it like,
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
Return false in all cases.
ok.. you have added a WebViewClient also..
then try it in this way...
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
this should work for you..
I am having a listView and a custom adapter, and i made an onclicklistener to a text view, now i want to open a link from that textview in webview, how can i do it?
After a lot of research i found the answer, it was really easy.
You have to set the onclickListener in custom adapter class, thats it and make a class to show a webview send a string to that class using intent.putextra();. The class where i am showing webview is this
public class Main extends Activity {
WebView myWebView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
Intent in = getIntent();
String url = in.getStringExtra(("url"));
myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setBlockNetworkImage(true);
myWebView.getSettings().setBlockNetworkLoads(true);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setPluginState(PluginState.ON);
myWebView.getSettings().setUserAgentString("Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3");
myWebView.loadUrl(url);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
class MyWebViewClient extends WebViewClient {
#Override
// show the web page in webview but not in web browser
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//1 option
getApplicationContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// 2 option
view.loadUrl(url);
return true;
}
}
}
I use WebChromeClient for opening a link to news.html on my server, it opens safari and shows the content, ok.
But...
When I implent WebViewClient shouldOverrideUrlLoading to intercept the call when it's link to a .pdf file (use another class for it) the WebChromeClient link to news.html stays in webview and does not open safari anymore...
I am doing something wrong, but what?
Code snippet: (links are long so I shortened it)
myWebView = (WebView)findViewById(R.id.webView);
myWebView.getSettings().setJavaScriptEnabled(true);
//only to catch url override
myWebView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("http://www.domain.nl/pdf")){
Intent i = new Intent();
i.putExtra("url", url);
i.setClassName("nl.domain.domain", "nl.domain.domain.PdfActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
return true ;
}
else {
return false ;
}
}
});
myWebView.setWebChromeClient(new WebChromeClient());
//loading
myWebView.loadUrl("http://www.domain.nl/news.html");
return false; means that the url wasn't handled and it should be opened in the WebView. If you want to open the url in an external browser you need to explicitly do it.
myWebView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("http://www.domain.nl/pdf")){
Intent i = new Intent();
i.putExtra("url", url);
i.setClassName("nl.domain.domain", "nl.domain.domain.PdfActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
return true ;
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url));
return true;
}
});
To open the PDF file url :
add the "http://docs.google.com/viewerembedded=true&url=" string at starting of PDF file url string...
try this it work
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView;
webView = new WebView(this);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setPluginsEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
if (webUrl.equals(XmlFileUrl.MemberDownloadAppForm)) {
webUrl = "http://docs.google.com/viewerembedded=true&url=" + webUrl;
}
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl(url);
setContentView(webView);
}
An example that helped me to do something similar Here
For geolocation add:
myWebView.getSettings().setGeolocationEnabled(true);
and :
private class MyWebChromeClient extends WebChromeClient {
.........
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback)
{
// callback.invoke(String origin, boolean allow, boolean remember);
callback.invoke(origin, true, false);
}
}