Say, I set my WebView into example.com then I clicked on the page and load the example.com/about.
In the WebView I've injected Javascript to modify the HTML on the example.com, and it worked, and the problem is, how to inject another JavaScript to modify example.com/about. I mean how to inject multiple JavaScript to a multiple page of WebView?
public class MainActivity extends AppCompatActivity {
WebView mWebView;
private int getScale() {
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
Double val = new Double(width) / new Double(100);
val = val * 100d;
return val.intValue();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
mWebView.setWebViewClient(new WebViewClient());
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// Inject CSS when page is done loading
injectCSS();
mWebView.loadUrl("javascript:var greeting = function (name) {\n" +
" console.log(\"Great to see you,\" + \" \" + name);\n" +
"};");
super.onPageFinished(view, url);
//Inject JS to edit html
injectScriptFile(view, "script.js"); // see below ...
// test if the script was loaded
view.loadUrl("javascript:setTimeout(test(), 500)");
}
private void injectScriptFile(WebView view, String scriptFile) {
InputStream input;
try {
input = getAssets().open(scriptFile);
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
// String-ify the script byte-array using BASE64 encoding !!!
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
view.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
// Tell the browser to BASE64-decode the string into your script !!!
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
mWebView.loadUrl("example.com");
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
}
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
mWebView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu); // Add menu items, second value is the id, use this in the onCreateOptionsMenu
menu.add(0, 1, 0, "Back");
menu.add(0, 2, 0, "Refresh");
menu.add(0, 3, 0, "Forward");
getMenuInflater().inflate(R.menu.menu_main, menu);
return true; // End of menu configuration
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 3: //If the ID equals 3 , go forward
mWebView.canGoForward();
item.setIcon(R.drawable.forward);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) { // Enables browsing to previous pages with the hardware back button
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { // Check if the key event was the BACK key and if there's history
mWebView.goBack();
return true;
} // If it wasn't the BACK key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
}
Related
I have an architecture where I am having a webview in MainActivity of my Android app. A page having a "Take Photo" button loads whenever user opens the app. On clicking "Take Photo" button, javascript will call dispatchTakePictureIntent() method defined in the Android app, which will redirect user to the Camera. Once, the user clicks the photo and submits it, I want to send the photo back to JS which in turn will make a AJAX call to the server to store the image.
I am facing trouble in developing the flow once user submits the photo. In my current implementation, I am able to store the image file locally and retrieve a file path, but I am unable to figure out how to use this file path in JS to get the file and send it on the server. Kindly help me out with this.
I have taken reference from this article: https://developer.android.com/training/camera/photobasics#TaskPath
MainActivity.java
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String FILE_PATH_PREFIX = "file:";
private String imageFilePath;
private String callbackFunction;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidPlatform.setUp(this, APPLICATION_NAME);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setGeolocationEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath());
webView.addJavascriptInterface(this, "Android");
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("URL to the page having take photo button");
}
#JavascriptInterface
public void dispatchTakePictureIntent(String _callbackFunction) {
this.callbackFunction = _callbackFunction;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = createImageFile();
if (photoFile != null) {
this.imageFilePath = FILE_PATH_PREFIX + photoFile.getAbsolutePath();
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} else {
Toast.makeText(getApplicationContext(), R.string.please_retry, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), R.string.no_camera_found, Toast.LENGTH_SHORT).show();
}
}
private File createImageFile() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "storephoto_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = null;
try {
image = File.createTempFile(imageFileName,".jpg", storageDir);
} catch (IOException e) {
Log.e(TAG, "Exception in createImageFile:", e);
}
return image;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if(resultCode == RESULT_OK && callbackFunction != null && imageFilePath != null) {
// What to do with imageFilePath?
//
// How to use it in Javascript to read and send image to backend server?
//
// Sample code if we send imageFilePath to JS:
// String callbackModule = String.format(TAKE_PICTURE_JS_MODULE, callbackFunction, imageFilePath);
// webView.evaluateJavascript(callbackModule, null);
}
}
}
}
Javascript
$takePhotoButton.click(function(e) {
e.preventDefault();
Android && Android.dispatchTakePictureIntent("takePhotoCallbackFn");
});
Note: Here it is necessary that user submits the photo through camera only and not via choosing/uploading an existing file.
I am trying to get the src of a captcha image found in a webview but when i type the below code the output says:
Uncaught TypeError: Cannot read property 'src' of null
and another question if i get the image src how can i put the image in an image view?
any help will be really appreciated
here is my code so far:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.wv) ;
mImgCaptcha = (ImageView) findViewById(R.id.imgCaptcha);
done = (Button) findViewById(R.id.done);
contentView = (TextView) findViewById(R.id.textView);
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.password);
code = (EditText) findViewById(R.id.code);
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
wv.getSettings().setDomStorageEnabled(true);
wv.loadUrl("https://noor.moe.gov.sa/NOOR/Login.aspx");
wv.loadUrl("javascript:var a = document.getElementById('imgCaptcha').src;");
System.out.println(wv.getUrl());
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
wv.loadUrl("javascript:var x = document.getElementById('tbPublic').value = '" + username.getText().toString() + "';");
wv.loadUrl("javascript:var x = document.getElementById('tbPrivate').value = '" + password.getText().toString() + "';");
wv.loadUrl("javascript:var x = document.getElementById('tbCaptcha').value = '" + code.getText().toString() + "';");
try {
Thread.sleep(2000);
wv.loadUrl("javascript:(function(){" +
"l=document.getElementById('btnLogin');" +
"e=document.createEvent('HTMLEvents');" +
"e.initEvent('click',true,true);" +
" l.dispatchEvent(e);" +
"})()");
} catch (InterruptedException e) {
e.printStackTrace();
}
It's because the page is not loaded yet when you are trying to query the DOM. You need to query the DOM when you can be sure that the page has loaded.
We need to set the WebViewClient for the webview and then listen to onPageFinished event. The code might look something like this:
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// you can now query the DOM.
webView.loadUrl("javascript:var a = document.getElementById('imgCaptcha').src;");
}
});
Further reading: https://developer.android.com/reference/android/webkit/WebViewClient#onPageFinished(android.webkit.WebView,%2520java.lang.String)
Here's my code for injecting CSS into a Webview:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Ubqari");
ww = (WebView) findViewById(R.id.ww);
ww.getSettings().setJavaScriptEnabled(true);
ww.getSettings().setDomStorageEnabled(true);
ww.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
injectCSS();
}
});
ww.loadUrl("http://ubqari.org");``
}
And here's injectCSS function:
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
ww.loadUrl("javascript:(function() {" +
"alert('Hello! I am an alert box!');"+
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
I don't know what's going wrong in this code. My style.css code is correct but the problem is in the onPageFinished section. It's not injecting the CSS when the page has finished loading. Any expert can answer me?
I am loading a webpage in WebView. There is a link in the webpage, which on desktop will download the file, but in the app the link should display a Toast saying the link is disabled for the app.
I am not sure how to get the value from href of the anchor tag, when the link is clicked.
<a class="btn btn-primary" download="http://xx.xxx.com/wp-content/uploads/2015/11/abc-27-15.mp3" href="http://xx.xxx.com/wp-content/uploads/2015/11/abc-27-15.mp3">
<i class="fa fa-download"></i> Download Audio</a>
Can someone share an idea or any sample code on how to do this.
EDIT:1
Here is what I am doing currently:
private static final String URL = "http://xx.xxx.com/wp-content/uploads/";
webView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
WebView.HitTestResult hr = ((WebView) v).getHitTestResult();
String extra = hr.getExtra();
if (extra != null && extra.startsWith(URL) && extra.endsWith(".mp3")) {
Log.d("WebviewActivity", "Extra: " + extra);
Log.d("WebviewActivity", "Contains URL");
return true;
}
}
return false;
}
});
The problem with this approach is:
When i click on the link, i get the url in extra. It works fine till here. But, from next time, no matter where i click on the webview, the same extra is being returned. So even if i click on an image after i click on the url, i get the same url in the extra. Not sure if i doing anything wrong. Or is this the correct approach.
Please let me know if you need any details.
EDIT:2
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// Get link-URL.
String url = (String) msg.getData().get("url");
// Do something with it.
if (url != null) {
Log.d(TAG, "URL: "+url);
}
}
};
webView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
WebView.HitTestResult hr = ((WebView) v).getHitTestResult();
if (hr.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
Message msg = mHandler.obtainMessage();
webView.requestFocusNodeHref(msg);
}
}
return false;
}
});
webView.loadUrl(mUrl);
}
Now, i get the URL that is clicked in the last action_down event. How to get the current URL?
EDIT 3 (Attempt with webviewclient:
private class MyWebViewClient extends WebViewClient {
private static final String URL = "xx.xxx.com/wp-content/uploads/";
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (!isFinishing())
mProgressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mProgressDialog.dismiss();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(WebviewActivity.this,
"Please check your internet " + "connection and try again",
Toast.LENGTH_SHORT).show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("xxx", "Url: " + url);
if(url.contains(URL)) {
Log.d("xxx", "Url Contains: " + URL);
return true;
}
return false;
}
}
mMyWebViewClient = new MyWebViewClient();
webView.setWebViewClient(mMyWebViewClient);
Output in logcat when the link is clicked:
03-01 15:38:19.402 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:553] focusedNodeChanged: isEditable [false]
03-01 15:38:19.428 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:253] updateKeyboardVisibility: type [0->0], flags [0], show [true],
03-01 15:38:19.428 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:326] hideKeyboard
03-01 15:38:19.429 19626-19626/com.xx.xxx D/cr_Ime: [InputMethodManagerWrapper.java:56] isActive: true
03-01 15:38:19.429 19626-19626/com.xx.xxx D/cr_Ime: [InputMethodManagerWrapper.java:65] hideSoftInputFromWindow
Because you are using a WebView and the link is not Java script this is very easy to achieve with a WebViewClient which you can use to monitor your WebView
myWebView.setWebViewClient( new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// check something unique to the urls you want to block
if (url.contains("xx.xxx.com")) {
Toast.make... //trigger the toast
return true; //with return true, the webview wont try rendering the url
}
return false; //let other links work normally
}
} );
It's possible that because your URL ends in .mp3 the file is being treated as a resource. You should also override the shouldInterceptRequest method of the WebViewClient to check this.
#Override
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
Log.d("XXX", "Url from API21 shouldInterceptRequest : " + url);
if (url.contains(URL)) {
return new WebResourceResponse("text/html", "UTF-8", "<html><body>No downloading from app</body></html>");
} else {
return null;
}
}
public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
Log.d("XXX", "Url from shouldInterceptRequest : " + url);
if (url.contains(URL)) {
return new WebResourceResponse("text/html", "UTF-8", "<html><body>No downloading from app</body></html>");
} else {
return null;
}
}
Most of the work can be done at the web page side itself. You have to write java script to identify which device is accessing the page (mobile, desktop etc) if its mobile then use java script binding technique to call the native android code to show Toast message.
http://developer.android.com/guide/webapps/webview.html
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
WebAppInterface.java
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();
}
}
YourHTML Page (this sample got a button click)
<input type="button" value="Say hello" onClick="showAndroidToast('Hello
Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
I am trying to use JavaScript in an Android webview. I used following code. I did not get color changed or offset height of body.
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new myJavaScriptInterface(webview), "jsInterface");
webview.loadUrl("file:///android_asset/sample/contents.html");
//webview.loadData("file:///android_asset/sample",convertStreamToString(inputStream), "text/html", "UTF-8");
webview.loadUrl("javascript:" +
"document.getElementsByTagName('p')[0].style.color='red';" +
"");
wbview.loadUrl("javascript:window.jsInterface.EchoText(document.body.offsetHeight);");
//webview.
}
class myJavaScriptInterface
{
WebView mywebview;
public myJavaScriptInterface(WebView webview)
{
this.mywebview=webview;
}
public void EchoText(String message)
{
Toast.makeText(mywebview.getContext(), message, Toast.LENGTH_SHORT).show();
}
}
What am I missing?
I think this is because your page is not loaded (still loading) when you are using webview.loadUrl("javascript:" + ...) statements.
Try the following...
webview.loadUrl("file:///android_asset/sample/contents.html");
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView webview, String url) {
webview.loadUrl("javascript:" +
"document.getElementsByTagName('p')[0].style.color='red';");
wbview.loadUrl("javascript:" +
"window.jsInterface.EchoText(document.body.offsetHeight);");
}
});