Good Day,
I have a webview in Android app which loads a resource that uses html and javascript:
WebView.getSettings().setJavaScriptEnabled(true);
//webView.getSettings().setDomStorageEnabled(true);
//webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//webView.getSettings().setLoadWithOverviewMode(true);
//webView.getSettings().setUseWideViewPort(true);
//webView.getSettings().setBuiltInZoomControls(true);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
//webView.loadUrl("file:///android_asset/Index.html");
webView.loadUrl("http://foo.com/newbilltemplate/");
The comments show you what I've tried so far. Also I tried local and online resource and the problem still exist.
The index.html page doesn't use Javascript but when a button is clicked it uses some Javascript calculations to display in the next page.
Thanks,
Related
In an Android activity I am displaying a webview.
WebView myWebView = (WebView) findViewById(R.id.webView1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/html/cloud.html");
The webview loads a local HTML file that builds a cloud of keywords with a javascript file. (source: http://www.goat1000.com/tagcanvas.php)
<script src="tagcanvas.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function() {
try {
TagCanvas.Start('myCanvas','tags',{depth: 0.8, maxSpeed: 0.03});
} catch(e) {
// something went wrong, hide the canvas container
document.getElementById('myCanvasContainer').style.display = 'none';
}
The keywords are generated from a list of HTML links defined in the HTML file
<div id="tags">
<ul>
<li>keyword1</li>
<li>keyword2</li>
<li>keyword3</li>
</ul>
</div>
When a user taps on a link, instead of staying in the webview and going to the corresponding location, I would like him to start a new Android activity, so obviously with Android code
I have found resources showing an example of how to make Android and Javascript "communicate" with an interface but I didn't manage to make it work in my case.
Edit:
My implementation thanks to the answer of Vlad
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Intent intent = new Intent(Act1.this, Act2.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //ugly solution to avoid starting 2 activities, not ideal but it works
startActivity(intent);
return true; //I always return true because I never want to open an HTML link
}
});
You can set a custom WebViewClient to the WebView, and intersect url loading in it:
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// check the URL, and do whatever you need to do according to the URL
// return true; // if you handled URL, and WebView should not load it
return false; // for the WebView to load the URL
}
});
I am building my first android application and having a issue. Basically i am trying to port my Youtube 2 Mp3 page built in PHP to a mobile application. I have successfully done this but the problem i am having is after converting to mp3 i am unable to download the mp3 file from the link printed on the page from the android app. It works fine directly from the webpage and it works fine if i have the app load the link in androids default browser ( Chrome ) but it does not work when i have the app load the link within WebView.
FILE: MainActivity.java
public class MainActivity extends AppCompatActivity {
WebView web;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
web = (WebView) findViewById(R.id.webView);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://www.bigjohn863.com/youtubetomp3/index.php");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public class myWebClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
}
WEBPAGE: http://www.bigjohn863.com/youtubetomp3/index.php
The webpage works as expected when loaded in a regular browser and it works fine if i use it in android default browser ( Chrome ), but if i change the code to only load clicked links in webview then when i click the link it does nothing.
Try adding this to your function shouldOverrideUrlLoading(WebView view, String url) after you validate the url. It will start a download similar to downloading from any webpage
if (url.endsWith(".mp3")) {
Uri source = Uri.parse(url);
// Make a new request pointing to the .mp3 url
DownloadManager.Request request = new DownloadManager.Request(source);
// appears the same in Notification bar while downloading
request.setDescription("Description for the DownloadManager Bar");
request.setTitle("YourMp3.mp3");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// save the file in the "Downloads" folder of SDCARD
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "MyMp3.mp3");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
Download your MP3 file
This code will defiantly not work in android web view because it contains the PHP code and PHP code is server side code and android web view can run only client side code.
If you want to run it then get the data from the server as URL and put it into the anchor tag or you can try with by putting an complete hard code URL inside anchor tag.
I feel pretty stupid for having to ask this but I can't for the life of me get it to work.
So I've searched around and found lots of help, guides, and etc for using the onPageFinished function in WebViewClient and my code is largely based on these.
Basically I have a function that is supposed to load a web page and then hides certain elements on that page with the onPageFinished. Instead of actually doing this though it hides the entire page and the webview displays the text "none".
When I comment out the onPageFinished function the webview loads the page just fine which leads me to believe that it has to be the javascript but according to the w3c site my javascript is correct for what I want to do...
So my question is this, Does anyone see the problem with the below code and/or anyone have a suggestion for something else that might accomplish my above stated goals?
Any help in getting this to work would be greatly appreciated.
Code:
public class MainActivity extends AppCompatActivity{
private WebView browser;
private String url = "https://www.google.com";
< onCreate calls cleanPage and other stuff >
public void cleanPage() {
browser = (WebView) findViewById(R.id.webview);
browser.getSettings().setJavaScriptEnabled(true);
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
browser.loadUrl("javascript:document.getElementById('lga').style.display='none';");
}
});
browser.loadUrl(url);
}
}
Notes:
-The above uses google as an example, lga is the id of the google banner div.
-browser and url are global because once I get cleanPage working I will add in other functions that will alter them as needed.
You need to add void(0); at the end of your javascript: URL. Otherwise, WebView replaces your current page with the result of the JS evaluation (in your case, that is the string "none").
So change this:
browser.loadUrl("javascript:document.getElementById('lga').style.display='none';");
to:
browser.loadUrl("javascript:document.getElementById('lga').style.display='none';void(0);");
I have a div called downloadapp that I'd like to display to users who visit my mobile website instead of using my Android app. So I need to hide that div for users who already use my app.
My code:
private void startWebView(String url) {
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
//On error, open local file
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/www/myerrorpage.html");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:document.getElementById('downloadapp').style.display = 'none';");
}
});
webView.loadUrl(url);
}
Problem:
My app loads the div first and its actually being displayed for a couple of seconds. Then suddenly, the whole webpage loaded in the app disappears and a blank page with the word "none" is the only thing that is left on the screen.
Is there something wrong with the way I try to hide the div "downloadapp" or what am I missing here?
What I want it to do is immediately hide the div before the webpage is being displayed.
This is happening on newer versions of WebView -- if your app is targeting API level 19 or above (KitKat), then if a javascript: URL returns a value, this value is interpreted as content for a new web page to open. In your case, as 'none' is the return value of the assignment, it is used as the content for a new page.
Just put void(0); at the end of your code in javascript: to prevent it from returning a value.
I am having a bit of trouble getting my application to correctly run some JS on a page using the onPageFinished method.
The code below is contained within a class I've created that extends AsyncTask to fetch and parse a JSON file held elsewhere.
I am able to fetch the JSON file correctly, parse the data and the url for the WebView is obtained and set. Everything works loads as it should until I attempt to run some JS with the onPageFinished method.
//onPostExecute method runs when the doInBackground method is completed
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
//Casting as WebView as findViewById doesnt explicity return a value type.
webView = (WebView) findViewById(R.id.webView);
//Obtaining the websettings of the webView
WebSettings webViewSettings = webView.getSettings();
//Setting Javascript enabled
webViewSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new webViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.loadUrl("document.getElementById('field_133').value = 'Test';");
Log.d("onPageFinished", "The Page has finished loading");
}
});
//Obtaining the first item in the cellRef List Array - From here we will access the Url data for the train operator.
parsedUrl = cellRef.get(0).getUrl();
//load the page we parsed from online file
webView.loadUrl(parsedUrl);
Log.d("loadUrl", "Now load the parsed Url");
}
All I am looking to do at the moment is test that the JS can correctly populate a textbox once the page has loaded with the value of "Test" - However, the WebView appears to be stuck in a loop of loading & refreshing (seeing repeated logcat prints of "The page has finished loading") when trying to run:
webView.loadUrl("document.getElementById('field_133').value = 'Test';");
Is this the correct way of trying to inject some JS into the WebView in Android? Apologies if there is something obvious missing, the majority of my experience lies in Swift.
Any help would be appreciated.
Thanks
Try "javascript:" before the code.
I use this, works perfectly:
loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()");