Android WebView crash using local web page - javascript

Can a webview in an android application crash due to errors in client side webpage. I tried loading a local webpage into the webview and crash that by throwing javascript errors and brute force attacks but the webview/app dint crash. I am working on a project which does analysis of the crashes(number of crashes etc.) by an apk.
JUST TELLING HOW TO CRASH A WEB-VIEW IN ANDROID APP WOULD BE REALLY HELPFUL, IRRESPECTIVE OF THE JAVA CODE BELOW.(Crashing should not done by throwing exception on some webview event. Basically, not from java.)
Following is the code I added in local webpage :
function myCrashFun() {
for(var i=0; i===i; i++) { Console.log("Hello123"); } //brute force attack
var num=1;
num.toUpperCase(); //typeError
}
</script><br>
<button type="button" onclick="myFunction()">Click Me!</button><br>
<button type="button" onclick="myCrashFun()">Click to crash!</button>
following is the code for webview activity using hello.html local webage :
public class WebviewTest extends Activity
{
WebView wv;
#Override
public void onBackPressed()
{
if (wv.canGoBack()) {
wv.goBack();
}
else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview_test);
wv = (WebView) findViewById(R.id.wv1);
//If the web page you plan to load in your WebView use JavaScript, you must enable JavaScript for your WebView.
wv.getSettings().setJavaScriptEnabled(true);
wv.setFocusable(true);
wv.setFocusableInTouchMode(true);
//WebSettings provides access to a variety of other settings that you might find useful.
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wv.getSettings().setDomStorageEnabled(true);
wv.getSettings().setDatabaseEnabled(true);
wv.getSettings().setAppCacheEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl("file:///android_asset/hello.html");
wv.setWebViewClient(new WebViewClient());
}
}
I don't want a webview to crash by throwing java exception/error. That part is already handled. Is there any way to crash the web view, using javascript or some client side technology..

Related

Android WebView won't load remote url from anchor tag

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.

webView loadURL not working on HTML button click

I have a webView in my application. The webView initially opens an HTML page I created with a few buttons on it. The buttons do various tasks (I'm trying to learn how to use webViews) like: 1)show android toast, 2)show javascript alert, 3)vibrate phone, 4)show current geolocation, 5)open google maps in webView.
It's this last one that's not working. I've searched this site and many others, but haven't found a solution that works.
I'm fairly certain I have all the manifest file 'stuff' correct (everything else is working, including the initial internet based web page). I'm happy to post that too though if you think it's needed.
My activity_main.xml file has never given me issues, but again, I'm happy to post that if you think it'll help.
Here are snippets from my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl(url); // this one works
myWebView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setGeolocationEnabled(true);
...
}
That all works and again the other html buttons work.
Then there's this:
public class WebAppInterface {
Context mContext;
//** Instantiate the interface and set the context *//
WebAppInterface(Context c) {
mContext = c;
}
//** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
#JavascriptInterface
public void vibrateDevice() {
Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
mVibrator.vibrate(500);
}
#JavascriptInterface
public void showMapCurPos() {
new Handler().post(new Runnable() {
String url2 = "http://www.google.com/maps/#53.001153,-95.0752916,15z";
#Override
public void run() {
myWebView.clearCache(true);//Here you call the methond in UI thread
myWebView.loadUrl(url2);
}
});
}
}
Everything works there, except for showMapCurPos(). I've already tried just a simple myWebView.loadUrl(...) along with several attempts at intents. Depending on what I've tried, sometimes that method crashes the app, but most of the time the new URL just doesn't get displayed and it stays on the original URL.
Please forgive me if this is a repeat question, but I really have searched this site and many others for an answer (probably for a solid 8 hours or so). I've tried many of those answers to no avail. I'm guessing it's something simple and has to do with my lack of understanding of webViews or activities or intents or all three or maybe even my newness to android development.
I can't write a comment yet, so I'm writing this as an answer.
You could try this answer:
myWebView.post(new Runnable() {...});
instead of using new Handler

Inject javascript into WebChromeClient

I know, you can inject javascript into an Android WebView. I already did that. However, I load a html5/javascript web app (not my own, so I have no access to the code) and I need to inject additional javascript. But this web app does not work properly in the standard WebView. The reason for that is probably:
"By default, a WebView provides no browser-like widgets, does not enable JavaScript and web page errors are ignored."
http://developer.android.com/reference/android/webkit/WebView.html
So, I enabled Javascript, but maybe this is due to the fact that it ignores webpage errors. However in the normal Chrome browser everythings works fine without any problems.
The webview does not work although I already enabled a lot of stuff:
webView = (WebView) findViewById( R.id.webView );
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setDomStorageEnabled(true);
webView.setBackgroundColor(0x00000000);
webView.setWebChromeClient( new WebChromeClient() );
webView.setWebViewClient( new WebViewListener() );
CookieManager.getInstance().setAcceptCookie(true);
So, is there some possibility to inject javascript into a normal WebChromeClient?
Or do you have any other guess what else I could enable or inject into the webview?
First, you need to setWebViewClient with a class that's derived form WebViewClient:
WebView webview = new WebView();
webview.setWebViewClient(new WebClient());
webview.loadUrl("stackoverflow.com");
then in WebClient, you wait for the page to load (onPageFinished). Then you loadUrl("javascript:[your javascript here]").
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)
{
// Obvious next step is: document.forms[0].submit()
view.loadUrl("javascript:document.forms[0].q.value='[android]'");
}
}
It is remembered wanting to do different JavaScript related tasks and so needing to enable a bunch of options and even set the browser type...here is those config options:
webView.setWebChromeClient(webChromeClient);
webView.setWebViewClient(new InsideWebViewClient(getBaseContext(), webView));
WebSettings settings = webView.getSettings();
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setBuiltInZoomControls(false);
settings.setUseWideViewPort(true);
settings.setJavaScriptEnabled(true);
settings.setSupportMultipleWindows(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setLoadsImagesAutomatically(true);
settings.setDomStorageEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setMediaPlaybackRequiresUserGesture(false);
// Call private class InsideWebViewClient
settings.setPluginState(WebSettings.PluginState.ON);
settings.setAllowFileAccess(true);
// settings.setUserAgentString("Mozilla/5.0");
settings.setUserAgentString("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36");
// webView.setInitialScale(50);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (0 != (getApplicationContext().getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE))
{ webView.setWebContentsDebuggingEnabled(true); }
}
for reference that was used with the same basic following:
https://github.com/cprcrack/VideoEnabledWebView/blob/01c7f758a409fabbc501cdf24efdf5b77400280f/app/src/main/java/name/cpr/ExampleActivity.java

interact with website using android webview

I run a forum which has a shoutbox plugin installed where users can talk to each other just like instant messaging. I decided to make what i thought would be a quick app which would just display the shoutbox so users could talk while on the go instead of using there browser. The problem i have found is that it all works great using android webview but when you try and send a shout it comes up with an error saying "fail!" as though it has no communication with the actual shoutbox.
My question is can webview be used like this or can it only be used to display a webpage with out actually interacting with it? Below is my code what i am using so you guys can see if i am missing anything and if so please point me in the right direction thanks.
public class splash extends Activity {
WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState)
{
final Activity mActivity = this;
super.onCreate(savedInstanceState);
// Adds Progrss bar Support
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.mainx);
// Makes Progress bar Visible
getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
mWebView = (WebView) findViewById( R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.myforum.com/forums/shoutbox.php");
mWebView.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
mActivity .setTitle("Loading...");
mActivity .setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
{
setTitle(R.string.title);
}
}
});
}
}
Creating and setting a
WebViewClient
subclass. It will be called when things happen that impact the rendering of the content, eg, errors or form submissions. You can also intercept URL loading here (via shouldOverrideUrlLoading()).

Is it possible to invoke Windows Phone code (i.e. Launch WebBrowserTask) from inside a WebBrowser control?

I have some static webpages as part of my Windows Phone 7 app. It would be very useful however for links that refer to non-local sites on the web to be able to launch the web browser i.e. invoke the WebBrowserTask. Also given that the WebBrowser control is embedded in a XAML page it would be great if I could (through javascript for example) invoke behaviours on the page from within the WebBrowser control.
Is this possible?
As I understand, you need to launch JavaScript in WP7 Browser. There are some security restictions. But most simple stuff works great. Have a look to "InvokeScript", IsScriptEnable on WebbrowserControl and "eval"
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
Wb.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(Wb_Navigated);
MouseLeftButtonDown += new MouseButtonEventHandler(MainPage_MouseLeftButtonDown);
Wb.NavigateToString("<html><body><form action='http://google.com/'></form></body></html>");
}
void Wb_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
Wb.InvokeScript("eval", "document.forms[0].submit();"); // Throws 80020101
}
private void MainPage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Wb.InvokeScript("eval", "document.forms[0].submit();"); // Works
}
}

Categories

Resources