I have some JSON content of a blog which i am displaying using loadDataWithBaseURL in WebView. Many articles of this blog have embedded youtube/vimeo videos.
Currently, all the videos are played inside the webview itself.
What i want to achieve is, when the user clicks to Play the Video, he should get the popup "Complete Action Using" Browser or YouTube App. In short, i dont want the videos to be played inside the webview of app.
I found questions where everyone was trying to avoid this popup.. Dont' know why i am not getting it.
Here is my code
public class DetailFragment extends Fragment {
String strTitle = null;
String strURL = null;
String strContent = null;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
AdView mAdView = (AdView) getView().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_fragment, container, false);
strTitle = getArguments().getString("title");
strURL = getArguments().getString("url");
strContent = getArguments().getString("content");
String contToDisplay = "<html><head><meta http-equiv='Content-Type' content='text/html' charset='UTF-8' /></head><body><style type='text/css'> img{width:80%;} .wp-image-42223{display:none;}</style>" + strContent+"</body></html>";
TextView title = (TextView) view.findViewById(R.id.title);
WebView desc = (WebView) view.findViewById(R.id.desc);
WebSettings ws = desc.getSettings();
ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
ws.setJavaScriptEnabled(true);
ws.setLoadWithOverviewMode(true);
ws.setUseWideViewPort(true);
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
title.setText(strTitle);
// desc.loadData(contToDisplay, "text/html; charset=UTF-8", null);
desc.loadDataWithBaseURL("about:blank",strContent,"text/html", "UTF-8", null);
return view;
}
}
any solution that wold make the videos load in browser or YouTube App would help.
NOTE
The content i am displaying in webview is in HTML format with iframe as one of the elements. Here is the sample data:
"<p>Some text</p>
<p><iframe src=\"https://www.youtube.com/embed/q7uBAtaK15I\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\"></iframe> </p>
<p>some more text</p>
This entire content is displayed in webview. What i want to achieve is when someone clicks on iframe, he should be prompted to complete action using that is, the person shd not be allowed to play the video in webview
I managed to achieve this using regex.
Here is what i did
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_fragment, container, false);
strTitle = getArguments().getString("title");
strURL = getArguments().getString("url");
strContent = getArguments().getString("content");
contToDisplay = "<html><head><meta http-equiv='Content-Type' content='text/html' charset='UTF-8' /><script type='text/javascript'></script></head><body><style type='text/css'> img{width:80%;} .wp-image-42223{display:none;} </style>" + strContent+"</body></html>";
TextView title = (TextView) view.findViewById(R.id.title);
TextView date = (TextView) view.findViewById(R.id.date);
TextView authorName = (TextView) view.findViewById(R.id.auth);
desc = (WebView) view.findViewById(R.id.desc);
setHasOptionsMenu(true);
WebSettings ws = desc.getSettings();
ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
ws.setJavaScriptEnabled(true);
ws.setLoadWithOverviewMode(true);
ws.setUseWideViewPort(true);
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.setSupportMultipleWindows(true);
ws.setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
title.setText(strTitle);
final String s = strContent;
final String regex = "(?<=<iframe src=\")[^\"]*";
final String regex2 = "<\\s*iframe[^>]*><\\s*/\\s*iframe>";
p = Pattern.compile(regex);
final Pattern p2 = Pattern.compile(regex2);
m = p.matcher(s);
m2 = p2.matcher(s);
evaluate(s,contToDisplay,this);
desc.loadData(value, "text/html; charset=UTF-8", null);
return view;
}
String evaluate(String token,String defaultValue, DetailFragment context){
value=null;
Matcher matcher=p.matcher(token);
if (matcher.find()) {
iframeURL=matcher.group();
String newURL = "Watch the Video Here";
value = m2.replaceAll(newURL);
}
if (value == null) {
value=defaultValue;
}
return value != null ? value : "";
}
Might help someone with similar issue.
This may help.we are loading a new url load in the correct native app.
desc.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view,
String url)
{
return true;
}
});
desc.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view,
String url)
{
if(url.contains("youtube.com")){
// Could be cleverer and use a regex return
return super.shouldOverrideUrlLoading(view, url);
}
return true;
});
If the links are embedded in an iframe (as the title suggested) you have to set a WebChromeClient to your webview and override the onCreateWindow-method:
#Override
public boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
WebView targetWebView = new WebView(view.getContext());
targetWebView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//simple url matching
if (url.contains("youtube.com") == true) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
view.getContex().startActivity(i);
}
view.stopLoading();
}
});
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(targetWebView);
resultMsg.sendToTarget();
return true;
}
And at the websettings of your webview, you have to set:
settings.setSupportMultipleWindows(true);
Related
I have a simple webview app that loads my website. Everything is ok, but when the user clicks on the Instagram icon in bottom of the webpage, I want to open the Instagram app instead of loading the Instagram webpage.
I'm trying to achieve this with shouldOverrideUrlLoading function and webview.geturl("https://www.instagram.com/").
The problem is when the user clicks on the Instagram icon, the URL doesn't change and stays default "http://archclub.ir/".
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://archclub.ir/login");
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
url = webView.getUrl();
Toast.makeText(MainActivity.this, webView.getUrl(), Toast.LENGTH_SHORT).show();
if (url.contains("https://www.instagram.com/")) {
Toast.makeText(MainActivity.this, "salam", Toast.LENGTH_SHORT).show();
webView.loadUrl("http://archclub.ir/");
}
return false;
}
});
}}
My problem is: When the user clicks on the Instagram icon on the website, the Toast.makeText(MainActivity.this, "salam", Toast.LENGTH_SHORT).show(); doesn't run.
I've checked this. I've debugged it. The problem is when the Instagram icon is clicked, the webview.geturl is equal to archclub.ir/login and doesn't change to instagram.com but the webview shows the Instagram page.
you were replacing the url over and over.
please replace this block of code instead of shouldOverrideUrlLoading method :
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// url = webView.getUrl(); // just omit this line
Toast.makeText(ali.this, webView.getUrl(), Toast.LENGTH_SHORT).show();
if (url.contains("https://www.instagram.com/")) {
Toast.makeText(ali.this, "salam", Toast.LENGTH_SHORT).show();
webView.loadUrl("http://archclub.ir/");
return true;
} else return false;
}
});
I have a WebView app which loads a url, I want to create a Settings Activity where user can customize settings..
My que is, How to make a RadioButton or Chooser which when clicked will open the Mobile version of Site, Similarly if Desktop Ver. is clicked, webview will load Desktop version...
By default webview loads mobile site, if you want to force load desktop site you can use
String newUA= "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4)Gecko/20100101 Firefox/4.0";
mWebView.getSettings().setUserAgentString(newUA);
use radio button to choose this settings. Use isChecked() to check radio button else load normal webview.
You can try code below
if(rbtnMobile.isChecked){
webview.getSettings().setJavaScriptEnabled(true);
webview.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");
webview.loadUrl(url);
}else{
webview.loadUrl(url);
}
Below is WebView code.
public class WebViewLinks extends Activity {
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
String Url = getIntent().getExtras().getString("Url");
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl(Url);
}
public class MyWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
You can use below code on button click or radio button selection.
Intent webViewIntent = new Intent(this, WebViewLinks.class);
webViewIntent.putExtra("Url", yourURL);
startActivity(webViewIntent);
see below example.
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.mobileview){
Intent webViewIntent = new Intent(this, WebViewLinks.class);
webViewIntent.putExtra("Url", mobileURL);
startActivity(webViewIntent);
}else if(checkedId == R.id.desktopview){
Intent webViewIntent = new Intent(this, WebViewLinks.class);
webViewIntent.putExtra("Url", deskTopURL);
startActivity(webViewIntent);
}
}
});
This similar SO question didn't help.
I have implemented a simple WebView to my MainActivity which loads a particular webpage on app launch. I have a TextView that shows the loading % of current webpage. The code is as below
public class MainActivity extends AppCompatActivity {
WebView webView;
final String homeUrl = "https://example.com";
String lastAccessedUrl = homeUrl;
WebChromeClient webChromeClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView) findViewById(R.id.browser);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
settings.setLoadsImagesAutomatically(false);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
webView.canGoBack();
webView.canGoForward();
webView.setWebViewClient(new MyBrowser());
webView.loadUrl(homeUrl);
webChromeClient = new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
TextView textView = (TextView) findViewById(R.id.loadingPercentage);
textView.setText(""+newProgress);
}
};
webView.setWebChromeClient(webChromeClient);
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
lastAccessedUrl = url;
view.loadUrl(url);
return true;
}
}
}
The problem I am facing is, the TextView shows loading % only for the first time the webpage loads. Then it is set to 100 permanently. Then if I click on any link on the first page, the TextView does not start from zero.
Do justify in comments if you vote down.
Any help would be appreciated.
There is no such problem with your code. Make sure you are clicking on a url. If you click on an expand view, it will just expand to show you certain data. It wont load as a new url. Click on say, www.stackoverflow.com and check if it's showing you loading percentage.
I´m new to android and i´m using the first time webview, fragment, drawer...
I have the problem that with my code after pressing fullscreen in the video my app is crashing.
And i have no idea what is going wrong...
WebViewFragmentVideos
public class WebViewFragmentVideos extends Fragment {
WebView webView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.Websitesenglish);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Updating the action bar title
getActivity().getActionBar().setTitle(menus[position]);
//Initializing and loading url in webview
webView = (WebView)v.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(url);
webView.setWebChromeClient(new MyChromeClient());
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
return v;}
class MyChromeClient extends WebChromeClient {
String url = getArguments().getString("url");
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
Intent intent = new Intent(null, LandVideoAct.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("video", url);
startActivity(intent);
}
}
}
and
LandVideoAct
public class LandVideoAct extends Activity {
WebView webView, fullweb;
String url = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
setContentView(R.layout.landfull);
url = getIntent().getStringExtra("video") + "?fs=1";
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
webView = (WebView) findViewById(R.id.fullwebview);
if (Build.VERSION.SDK_INT < 8) {
webView.getSettings().setPluginsEnabled(true);
} else {
webView.getSettings().setPluginState(PluginState.ON);
}
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
LandVideoAct.this.finish();
}
});
webView.loadUrl(url);
}}
I hope you dudes can help me with my problem.
Thank you!!
this piece of line of code is not allowed in android.
Intent intent = new Intent(null, LandVideoAct.class);
coming to your crash problem. Its mainly because of a above line of code. When full screen of video in webview is called , its gives call to android system ie onShowCustomView(View view, CustomViewCallback callback). Where you above line of code is failing.
instead of that use activity context or application context
Intent intent = new Intent(context, LandVideoAct.class);
I am encountering a problem where I cannot put the URL in the stringbuilder. What I am trying to accomplish here is to just get a particular part of the page. Here is the webpage I am trying to get the content off of:
http://www.google.com/finance/company_news?q=CURRENCY%3AUSD&ei=hYbQUcC3LJS80QHnDA
Here is the part of the website I want to only show in my WebView:
http://oi44.tinypic.com/2ilnhwi.jpg
Here is my code:
public class WebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
StringBuilder builder = new StringBuilder("");
builder.append("javascript:document.getElementById('gb') .style.visibility= 'hidden';");
builder.append("document.getElementById('gb') .style.display = 'none' ;");
builder.append("document.getElementById('appbar').style.visibility= 'hidden';");
builder.append("document.getElementById('appbar').style.display = 'none' ;");
builder.append("document.getElementById('gf-nav').style.visibility= 'hidden';");
builder.append("document.getElementById('gf-nav').style.display = 'none' ;");
view.loadUrl(builder.toString());
}
}
private void AddListenerOnButton() {
spinner = (Spinner) getView().findViewById(R.id.spinner);
final WebView webView = (WebView) getView().findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String text1 = spinner.getSelectedItem().toString().trim();
WebClient wc = new WebClient();
if (text1.equals("US Dollar - USD")) {
//webView.loadUrl("http://www.google.com/finance/company_news?q=CURRENCY%3AUSD&ei=hYbQUcC3LJS80QHnDA");
wc.onPageFinished(webView, "http://www.google.com/finance/company_news?q=CURRENCY%3AUSD&ei=hYbQUcC3LJS80QHnDA");
wc.shouldOverrideUrlLoading(webView, "http://www.google.com/finance/company_news?q=CURRENCY%3AUSD&ei=hYbQUcC3LJS80QHnDA");
}
}
I have tried everything, but the whole webpage is still showing. What am I doing wrong? Is it something else that is wrong? Any help would be greatly appreciated.
My current code is wrapped in an entire function() wrapper, which works fine, maybe you could try that out:
builder.append("javascript:(function() {");
builder.append("document.getElementById('gb') .style.visibility= 'hidden';");
builder.append("document.getElementById('gb') .style.display = 'none' ;");
builder.append("document.getElementById('appbar').style.visibility= 'hidden';");
builder.append("document.getElementById('appbar').style.display = 'none' ;");
builder.append("document.getElementById('gf-nav').style.visibility= 'hidden';");
builder.append("document.getElementById('gf-nav').style.display = 'none' ;");
builder.append("})()");
Edit: Forgot a couple of parentheses at the end of the (function(){})