Comments (69)
I solve change InAppBrowser plugin. I merged solution on https://stackoverflow.com/questions/51168600/webview-open-camera-from-input-field-without-filechooser.
Follow the changes:
See the changes made in InAppBrowser class from plugin version 3.0.0
1 - include imports:
import android.app.Activity;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
2 - declare variavel;
private String mCM;
3 - Replace onShowFileChooser code
// For Android 5.0+
public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
LOG.d(LOG_TAG, "File Chooser 5.0+");
// If callback exists, finish it.
if(mUploadCallbackLollipop != null) {
mUploadCallbackLollipop.onReceiveValue(null);
}
mUploadCallbackLollipop = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(cordova.getActivity().getPackageManager()) != null) {
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(LOG_TAG, "Image file creation failed", ex);
}
if(photoFile != null){
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
}else{
takePictureIntent = null;
}
}
// Create File Chooser Intent
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if(takePictureIntent != null){
intentArray = new Intent[]{takePictureIntent};
}else{
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Selecione a imagem");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
// Run cordova startActivityForResult
cordova.startActivityForResult(InAppBrowser.this, chooserIntent, FILECHOOSER_REQUESTCODE);
return true;
}
4 - create method
private File createImageFile() throws IOException{
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
5 - Replace onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// For Android >= 5.0
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
LOG.d(LOG_TAG, "onActivityResult (For Android >= 5.0)");
Uri[] results = null;
//Check if response is positive
if(resultCode== Activity.RESULT_OK){
if(requestCode == FILECHOOSER_REQUESTCODE){
if(null == mUploadCallbackLollipop){
return;
}
if(intent == null || intent.getData() == null){
//Capture Photo if no image available
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = intent.getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUploadCallbackLollipop .onReceiveValue(results);
mUploadCallbackLollipop = null;
}
// For Android < 5.0
else {
LOG.d(LOG_TAG, "onActivityResult (For Android < 5.0)");
// If RequestCode or Callback is Invalid
if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) {
super.onActivityResult(requestCode, resultCode, intent);
return;
}
if (null == mUploadCallback) return;
Uri result = intent == null || resultCode != cordova.getActivity().RESULT_OK ? null : intent.getData();
mUploadCallback.onReceiveValue(result);
mUploadCallback = null;
}
}
from cordova-plugin-inappbrowser.
Please, try add permissions in config.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
from cordova-plugin-inappbrowser.
Does not have a reference in input field? I have not yet reached this level in the application. I just trusted that image was in the input field. To find this solution was too hard, don't make me sad :(
from cordova-plugin-inappbrowser.
Please, install [email protected] in you ionic app and replace the content file node_modules\cordova-plugin-inappbrowser\src\android\InAppBrowser.java with below code. Try app and give feeback, ok?
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.inappbrowser;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.provider.Browser;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaHttpAuthHandler;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginManager;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Locale;;
@SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private static final String NULL = "null";
protected static final String LOG_TAG = "InAppBrowser";
private static final String SELF = "_self";
private static final String SYSTEM = "_system";
private static final String EXIT_EVENT = "exit";
private static final String LOCATION = "location";
private static final String ZOOM = "zoom";
private static final String HIDDEN = "hidden";
private static final String LOAD_START_EVENT = "loadstart";
private static final String LOAD_STOP_EVENT = "loadstop";
private static final String LOAD_ERROR_EVENT = "loaderror";
private static final String CLEAR_ALL_CACHE = "clearcache";
private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
private static final String HARDWARE_BACK_BUTTON = "hardwareback";
private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction";
private static final String SHOULD_PAUSE = "shouldPauseOnSuspend";
private static final Boolean DEFAULT_HARDWARE_BACK = true;
private static final String USER_WIDE_VIEW_PORT = "useWideViewPort";
private static final String TOOLBAR_COLOR = "toolbarcolor";
private static final String CLOSE_BUTTON_CAPTION = "closebuttoncaption";
private static final String CLOSE_BUTTON_COLOR = "closebuttoncolor";
private static final String HIDE_NAVIGATION = "hidenavigationbuttons";
private static final String NAVIGATION_COLOR = "navigationbuttoncolor";
private static final String HIDE_URL = "hideurlbar";
private static final String FOOTER = "footer";
private static final String FOOTER_COLOR = "footercolor";
private static final List customizableOptions = Arrays.asList(CLOSE_BUTTON_CAPTION, TOOLBAR_COLOR, NAVIGATION_COLOR, CLOSE_BUTTON_COLOR, FOOTER_COLOR);
private InAppBrowserDialog dialog;
private WebView inAppWebView;
private EditText edittext;
private CallbackContext callbackContext;
private boolean showLocationBar = true;
private boolean showZoomControls = true;
private boolean openWindowHidden = false;
private boolean clearAllCache = false;
private boolean clearSessionCache = false;
private boolean hadwareBackButton = true;
private boolean mediaPlaybackRequiresUserGesture = false;
private boolean shouldPauseInAppBrowser = false;
private boolean useWideViewPort = true;
private ValueCallback<Uri> mUploadCallback;
private ValueCallback<Uri[]> mUploadCallbackLollipop;
private final static int FILECHOOSER_REQUESTCODE = 1;
private final static int FILECHOOSER_REQUESTCODE_LOLLIPOP = 2;
private String closeButtonCaption = "";
private String closeButtonColor = "";
private int toolbarColor = android.graphics.Color.LTGRAY;
private boolean hideNavigationButtons = false;
private String navigationButtonColor = "";
private boolean hideUrlBar = false;
private boolean showFooter = false;
private String footerColor = "";
private String[] allowedSchemes;
private String mCM;
/**
* Executes the request and returns PluginResult.
*
* @param action the action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext the callbackContext used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("open")) {
this.callbackContext = callbackContext;
final String url = args.getString(0);
String t = args.optString(1);
if (t == null || t.equals("") || t.equals(NULL)) {
t = SELF;
}
final String target = t;
final HashMap<String, String> features = parseFeature(args.optString(2));
LOG.d(LOG_TAG, "target = " + target);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String result = "";
// SELF
if (SELF.equals(target)) {
LOG.d(LOG_TAG, "in self");
/* This code exists for compatibility between 3.x and 4.x versions of Cordova.
* Previously the Config class had a static method, isUrlWhitelisted(). That
* responsibility has been moved to the plugins, with an aggregating method in
* PluginManager.
*/
Boolean shouldAllowNavigation = null;
if (url.startsWith("javascript:")) {
shouldAllowNavigation = true;
}
if (shouldAllowNavigation == null) {
try {
Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
shouldAllowNavigation = (Boolean)iuw.invoke(null, url);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
if (shouldAllowNavigation == null) {
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
PluginManager pm = (PluginManager)gpm.invoke(webView);
Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
shouldAllowNavigation = (Boolean)san.invoke(pm, url);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
// load in webview
if (Boolean.TRUE.equals(shouldAllowNavigation)) {
LOG.d(LOG_TAG, "loading in webview");
webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.SCHEME_TEL))
{
try {
LOG.d(LOG_TAG, "loading in dialer");
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
// load in InAppBrowser
else {
LOG.d(LOG_TAG, "loading in InAppBrowser");
result = showWebPage(url, features);
}
}
// SYSTEM
else if (SYSTEM.equals(target)) {
LOG.d(LOG_TAG, "in system");
result = openExternal(url);
}
// BLANK - or anything else
else {
LOG.d(LOG_TAG, "in blank");
result = showWebPage(url, features);
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
});
}
else if (action.equals("close")) {
closeDialog();
}
else if (action.equals("injectScriptCode")) {
String jsWrapper = null;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId());
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectScriptFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleCode")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("show")) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.show();
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
else if (action.equals("hide")) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.hide();
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
else {
return false;
}
return true;
}
/**
* Called when the view navigates.
*/
@Override
public void onReset() {
closeDialog();
}
/**
* Called when the system is about to start resuming a previous activity.
*/
@Override
public void onPause(boolean multitasking) {
if (shouldPauseInAppBrowser) {
inAppWebView.onPause();
}
}
/**
* Called when the activity will start interacting with the user.
*/
@Override
public void onResume(boolean multitasking) {
if (shouldPauseInAppBrowser) {
inAppWebView.onResume();
}
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
closeDialog();
}
/**
* Inject an object (script or style) into the InAppBrowser WebView.
*
* This is a helper method for the inject{Script|Style}{Code|File} API calls, which
* provides a consistent method for injecting JavaScript code into the document.
*
* If a wrapper string is supplied, then the source string will be JSON-encoded (adding
* quotes) and wrapped using string formatting. (The wrapper string should have a single
* '%s' marker)
*
* @param source The source object (filename or script/style text) to inject into
* the document.
* @param jsWrapper A JavaScript string to wrap the source string in, so that the object
* is properly injected, or null if the source string is JavaScript text
* which should be executed directly.
*/
private void injectDeferredObject(String source, String jsWrapper) {
if (inAppWebView!=null) {
String scriptToInject;
if (jsWrapper != null) {
org.json.JSONArray jsonEsc = new org.json.JSONArray();
jsonEsc.put(source);
String jsonRepr = jsonEsc.toString();
String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1);
scriptToInject = String.format(jsWrapper, jsonSourceString);
} else {
scriptToInject = source;
}
final String finalScriptToInject = scriptToInject;
this.cordova.getActivity().runOnUiThread(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
// This action will have the side-effect of blurring the currently focused element
inAppWebView.loadUrl("javascript:" + finalScriptToInject);
} else {
inAppWebView.evaluateJavascript(finalScriptToInject, null);
}
}
});
} else {
LOG.d(LOG_TAG, "Can't inject code into the system browser");
}
}
/**
* Put the list of features into a hash map
*
* @param optString
* @return
*/
private HashMap<String, String> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, String> map = new HashMap<String, String>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
String value = option.nextToken();
if (!customizableOptions.contains(key)){
value = value.equals("yes") || value.equals("no") ? value : "yes";
}
map.put(key, value);
}
}
return map;
}
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @return "" if ok, or error message.
*/
public String openExternal(String url) {
try {
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW);
// Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
// Adding the MIME type to http: URLs causes them to not be handled by the downloader.
Uri uri = Uri.parse(url);
if ("file".equals(uri.getScheme())) {
intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri));
} else {
intent.setData(uri);
}
intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName());
this.cordova.getActivity().startActivity(intent);
return "";
// not catching FileUriExposedException explicitly because buildtools<24 doesn't know about it
} catch (java.lang.RuntimeException e) {
LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString());
return e.toString();
}
}
/**
* Closes the dialog
*/
public void closeDialog() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final WebView childView = inAppWebView;
// The JS protects against multiple calls, so this should happen only when
// closeDialog() is called by other native code.
if (childView == null) {
return;
}
childView.setWebViewClient(new WebViewClient() {
// NB: wait for about:blank before dismissing
public void onPageFinished(WebView view, String url) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
});
// NB: From SDK 19: "If you call methods on WebView from any thread
// other than your app's UI thread, it can cause unexpected results."
// http://developer.android.com/guide/webapps/migrating.html#Threads
childView.loadUrl("about:blank");
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
public void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
/**
* Can the web browser go back?
* @return boolean
*/
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
/**
* Has the user set the hardware back button to go back
* @return boolean
*/
public boolean hardwareBack() {
return hadwareBackButton;
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.inAppWebView.canGoForward()) {
this.inAppWebView.goForward();
}
}
/**
* Navigate to the new page
*
* @param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.inAppWebView.loadUrl("http://" + url);
} else {
this.inAppWebView.loadUrl(url);
}
this.inAppWebView.requestFocus();
}
/**
* Should we show the location bar?
*
* @return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
private InAppBrowser getInAppBrowser(){
return this;
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @param features jsonObject
*/
public String showWebPage(final String url, HashMap<String, String> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
openWindowHidden = false;
mediaPlaybackRequiresUserGesture = false;
if (features != null) {
String show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.equals("yes") ? true : false;
}
if(showLocationBar) {
String hideNavigation = features.get(HIDE_NAVIGATION);
String hideUrl = features.get(HIDE_URL);
if(hideNavigation != null) hideNavigationButtons = hideNavigation.equals("yes") ? true : false;
if(hideUrl != null) hideUrlBar = hideUrl.equals("yes") ? true : false;
}
String zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.equals("yes") ? true : false;
}
String hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.equals("yes") ? true : false;
}
String hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.equals("yes") ? true : false;
} else {
hadwareBackButton = DEFAULT_HARDWARE_BACK;
}
String mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION);
if (mediaPlayback != null) {
mediaPlaybackRequiresUserGesture = mediaPlayback.equals("yes") ? true : false;
}
String cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.equals("yes") ? true : false;
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.equals("yes") ? true : false;
}
}
String shouldPause = features.get(SHOULD_PAUSE);
if (shouldPause != null) {
shouldPauseInAppBrowser = shouldPause.equals("yes") ? true : false;
}
String wideViewPort = features.get(USER_WIDE_VIEW_PORT);
if (wideViewPort != null ) {
useWideViewPort = wideViewPort.equals("yes") ? true : false;
}
String closeButtonCaptionSet = features.get(CLOSE_BUTTON_CAPTION);
if (closeButtonCaptionSet != null) {
closeButtonCaption = closeButtonCaptionSet;
}
String closeButtonColorSet = features.get(CLOSE_BUTTON_COLOR);
if (closeButtonColorSet != null) {
closeButtonColor = closeButtonColorSet;
}
String toolbarColorSet = features.get(TOOLBAR_COLOR);
if (toolbarColorSet != null) {
toolbarColor = android.graphics.Color.parseColor(toolbarColorSet);
}
String navigationButtonColorSet = features.get(NAVIGATION_COLOR);
if (navigationButtonColorSet != null) {
navigationButtonColor = navigationButtonColorSet;
}
String showFooterSet = features.get(FOOTER);
if (showFooterSet != null) {
showFooter = showFooterSet.equals("yes") ? true : false;
}
String footerColorSet = features.get(FOOTER_COLOR);
if (footerColorSet != null) {
footerColor = footerColorSet;
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
private View createCloseButton(int id){
View _close;
Resources activityRes = cordova.getActivity().getResources();
if (closeButtonCaption != "") {
// Use TextView for text
TextView close = new TextView(cordova.getActivity());
close.setText(closeButtonCaption);
close.setTextSize(20);
if (closeButtonColor != "") close.setTextColor(android.graphics.Color.parseColor(closeButtonColor));
close.setGravity(android.view.Gravity.CENTER_VERTICAL);
close.setPadding(this.dpToPixels(10), 0, this.dpToPixels(10), 0);
_close = close;
}
else {
ImageButton close = new ImageButton(cordova.getActivity());
int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
Drawable closeIcon = activityRes.getDrawable(closeResId);
if (closeButtonColor != "") close.setColorFilter(android.graphics.Color.parseColor(closeButtonColor));
close.setImageDrawable(closeIcon);
close.setScaleType(ImageView.ScaleType.FIT_CENTER);
if (Build.VERSION.SDK_INT >= 16)
close.getAdjustViewBounds();
_close = close;
}
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
_close.setLayoutParams(closeLayoutParams);
if (Build.VERSION.SDK_INT >= 16)
_close.setBackground(null);
else
_close.setBackgroundDrawable(null);
_close.setContentDescription("Close Button");
_close.setId(Integer.valueOf(id));
_close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
return _close;
}
@SuppressLint("NewApi")
public void run() {
// CB-6702 InAppBrowser hangs when opening more than one instance
if (dialog != null) {
dialog.dismiss();
};
// Let's create the main dialog
dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setInAppBroswer(getInAppBrowser());
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
//Please, no more black!
toolbar.setBackgroundColor(toolbarColor);
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(Integer.valueOf(1));
// Back button
ImageButton back = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(Integer.valueOf(2));
Resources activityRes = cordova.getActivity().getResources();
int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
Drawable backIcon = activityRes.getDrawable(backResId);
if (navigationButtonColor != "") back.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
if (Build.VERSION.SDK_INT >= 16)
back.setBackground(null);
else
back.setBackgroundDrawable(null);
back.setImageDrawable(backIcon);
back.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
back.getAdjustViewBounds();
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
ImageButton forward = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(Integer.valueOf(3));
int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
Drawable fwdIcon = activityRes.getDrawable(fwdResId);
if (navigationButtonColor != "") forward.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
if (Build.VERSION.SDK_INT >= 16)
forward.setBackground(null);
else
forward.setBackgroundDrawable(null);
forward.setImageDrawable(fwdIcon);
forward.setScaleType(ImageView.ScaleType.FIT_CENTER);
forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
forward.getAdjustViewBounds();
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(Integer.valueOf(4));
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Header Close/Done button
View close = createCloseButton(5);
toolbar.addView(close);
// Footer
RelativeLayout footer = new RelativeLayout(cordova.getActivity());
int _footerColor;
if(footerColor != ""){
_footerColor = Color.parseColor(footerColor);
}else{
_footerColor = android.graphics.Color.LTGRAY;
}
footer.setBackgroundColor(_footerColor);
RelativeLayout.LayoutParams footerLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44));
footerLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
footer.setLayoutParams(footerLayout);
if (closeButtonCaption != "") footer.setPadding(this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8));
footer.setHorizontalGravity(Gravity.LEFT);
footer.setVerticalGravity(Gravity.BOTTOM);
View footerClose = createCloseButton(7);
footer.addView(footerClose);
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));
// File Chooser Implemented ChromeClient
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView) {
// For Android 5.0+
public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if(Build.VERSION.SDK_INT >=23 && (cordova.getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || cordova.getActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
cordova.getActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
LOG.d(LOG_TAG, "File Chooser 5.0+");
// If callback exists, finish it.
if(mUploadCallbackLollipop != null) {
mUploadCallbackLollipop.onReceiveValue(null);
}
mUploadCallbackLollipop = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(cordova.getActivity().getPackageManager()) != null) {
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(LOG_TAG, "Image file creation failed", ex);
}
if(photoFile != null){
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
}else{
takePictureIntent = null;
}
}
// Create File Chooser Intent
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if(takePictureIntent != null){
intentArray = new Intent[]{takePictureIntent};
}else{
intentArray = new Intent[0];
}
Locale localeInfo = cordova.getActivity().getApplicationContext().getResources()
.getConfiguration().getLocales().get(0);
String lang = localeInfo.toLanguageTag();
String title;
if (lang.startsWith("en"))
{
title = "Choose the source";
} else if (lang.startsWith("es"))
{
title = "Seleccione el origen";
} else
{
title = "Escolha a origem";
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, title);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
// Run cordova startActivityForResult
cordova.startActivityForResult(InAppBrowser.this, chooserIntent, FILECHOOSER_REQUESTCODE);
return true;
}
// For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
LOG.d(LOG_TAG, "File Chooser 4.1+");
// Call file chooser for Android 3.0+
openFileChooser(uploadMsg, acceptType);
}
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType)
{
LOG.d(LOG_TAG, "File Chooser 3.0+");
mUploadCallback = uploadMsg;
Intent content = new Intent(Intent.ACTION_GET_CONTENT);
content.addCategory(Intent.CATEGORY_OPENABLE);
// run startActivityForResult
cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE);
}
});
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(showZoomControls);
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
}
String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
String appendUserAgent = preferences.getString("AppendUserAgent", null);
if (overrideUserAgent != null) {
settings.setUserAgentString(overrideUserAgent);
}
if (appendUserAgent != null) {
settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent);
}
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if (enableDatabase) {
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
if (clearAllCache) {
CookieManager.getInstance().removeAllCookie();
} else if (clearSessionCache) {
CookieManager.getInstance().removeSessionCookie();
}
// Enable Thirdparty Cookies on >=Android 5.0 device
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(inAppWebView,true);
}
inAppWebView.loadUrl(url);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(useWideViewPort);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar if they haven't been disabled
if (!hideNavigationButtons) toolbar.addView(actionButtonContainer);
if (!hideUrlBar) toolbar.addView(edittext);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
RelativeLayout webViewLayout = new RelativeLayout(cordova.getActivity());
webViewLayout.addView(inAppWebView);
main.addView(webViewLayout);
// Don't add the footer unless it's been enabled
if (showFooter) {
webViewLayout.addView(footer);
}
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
// the goal of openhidden is to load the url and not display it
// Show() needs to be called to cause the URL to be loaded
if(openWindowHidden) {
dialog.hide();
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
private File createImageFile() throws IOException{
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
/**
* Create a new plugin success result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
*/
private void sendUpdate(JSONObject obj, boolean keepCallback) {
sendUpdate(obj, keepCallback, PluginResult.Status.OK);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
* @param status the status code to return to the JavaScript environment
*/
private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
if (callbackContext != null) {
PluginResult result = new PluginResult(status, obj);
result.setKeepCallback(keepCallback);
callbackContext.sendPluginResult(result);
if (!keepCallback) {
callbackContext = null;
}
}
}
/**
* Receive File Data from File Chooser
*
* @param requestCode the requested code from chromeclient
* @param resultCode the result code returned from android system
* @param intent the data from android file chooser
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// For Android >= 5.0
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
LOG.d(LOG_TAG, "onActivityResult (For Android >= 5.0)");
Uri[] results = null;
//Check if response is positive
if(resultCode== Activity.RESULT_OK){
if(requestCode == FILECHOOSER_REQUESTCODE){
if(null == mUploadCallbackLollipop){
return;
}
if(intent == null || intent.getData() == null){
//Capture Photo if no image available
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = intent.getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUploadCallbackLollipop .onReceiveValue(results);
mUploadCallbackLollipop = null;
}
// For Android < 5.0
else {
LOG.d(LOG_TAG, "onActivityResult (For Android < 5.0)");
// If RequestCode or Callback is Invalid
if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) {
super.onActivityResult(requestCode, resultCode, intent);
return;
}
if (null == mUploadCallback) return;
Uri result = intent == null || resultCode != cordova.getActivity().RESULT_OK ? null : intent.getData();
mUploadCallback.onReceiveValue(result);
mUploadCallback = null;
}
}
/**
* The webview client receives notifications about appView
*/
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
/**
* Constructor.
*
* @param webView
* @param mEditText
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
this.webView = webView;
this.edittext = mEditText;
}
/**
* Override the URL that should be loaded
*
* This handles a small subset of all the URIs that would be encountered.
*
* @param webView
* @param url
*/
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
} else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
} else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:" + address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
// Test for whitelisted custom scheme names like mycoolapp:// or twitteroauthresponse:// (Twitter Oauth Response)
else if (!url.startsWith("http:") && !url.startsWith("https:") && url.matches("^[a-z]*://.*?$")) {
if (allowedSchemes == null) {
String allowed = preferences.getString("AllowedSchemes", "");
allowedSchemes = allowed.split(",");
}
if (allowedSchemes != null) {
for (String scheme : allowedSchemes) {
if (url.startsWith(scheme)) {
try {
JSONObject obj = new JSONObject();
obj.put("type", "customscheme");
obj.put("url", url);
sendUpdate(obj, true);
return true;
} catch (JSONException ex) {
LOG.e(LOG_TAG, "Custom Scheme URI passed in has caused a JSON error.");
}
}
}
}
}
return false;
}
/*
* onPageStarted fires the LOAD_START_EVENT
*
* @param view
* @param url
* @param favicon
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc = "";
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
}
else
{
// Assume that everything is HTTP at this point, because if we don't specify,
// it really should be. Complain loudly about this!!!
LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI");
newloc = "http://" + url;
}
// Update the UI if we haven't already
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_START_EVENT);
obj.put("url", newloc);
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
}
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush();
} else {
CookieSyncManager.getInstance().sync();
}
// https://issues.apache.org/jira/browse/CB-11248
view.clearFocus();
view.requestFocus();
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
obj.put("url", url);
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", failingUrl);
obj.put("code", errorCode);
obj.put("message", description);
sendUpdate(obj, true, PluginResult.Status.ERROR);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
/**
* On received http auth request.
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
// Check if there is some plugin which can resolve this auth challenge
PluginManager pluginManager = null;
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
pluginManager = (PluginManager)gpm.invoke(webView);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
if (pluginManager == null) {
try {
Field pmf = webView.getClass().getField("pluginManager");
pluginManager = (PluginManager)pmf.get(webView);
} catch (NoSuchFieldException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) {
return;
}
// By default handle 401 like we'd normally do!
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
}
from cordova-plugin-inappbrowser.
@davidrevo That didn't work, keeps getting the same error
Hi @PlanB007,
Add after import android.widget.TextView the import android.content.ContentValues;
After change line private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q; to private boolean isAndroidQ = Build.VERSION.SDK_INT >= 29 and test;
from cordova-plugin-inappbrowser.
@davidrevo That didn't work, keeps getting the same error
Hi @PlanB007,
Add after import android.widget.TextView the import android.content.ContentValues;
After change line private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q; to private boolean isAndroidQ = Build.VERSION.SDK_INT >= 29 and test;This work for me! The only issue left is I can choose between the files folder & camcorder (video only). I want to acces the camera. The HTML is used is
<input accept="image/png, image/jpeg" type="file" capture="">
any idea? In chrome it opens the camera, and not the camcorder.
Do you mean you want to access camera not video recorder? Need to change this
Intent takePictureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
=>
Intent takePictureIntent = new Intent(MediaStore. ACTION_IMAGE_CAPTURE);
from cordova-plugin-inappbrowser.
This should be in the master branch. I don't want to take credit for this but people shouldn't have to find the github issue in order to get this fix. @PlanB007 or @davidrevo can one of you guys submit a pull request with this fix?
from cordova-plugin-inappbrowser.
the same with me ? now ,I can open camera but I can't get the Image from camera. I think the inappbrowser can't get the message from cordova plugin result.
from cordova-plugin-inappbrowser.
Hi, we have the same problem. Use this url to test: https://mobilehtml5.org/ts/?id=23
android using browser : open camera (ok)
android using inappbrowser.open : open file explorer (error)
ios using browser: open camera (ok)
ios using inappbrowser.open: open camera (ok)
config.xml
<preference name="phonegap-version" value="cli-8.1.1" />
<feature name="http://api.phonegap.com/1.0/camera" />
<plugin name="cordova-plugin-camera" source="npm">
<variable name="CAMERA_USAGE_DESCRIPTION" value="camera string." />
</plugin>
<plugin name="cordova-plugin-inappbrowser" source="npm" />
<plugin name="cordova-plugin-wkwebview-engine" source="npm" />
<feature name="CDVWKWebViewEngine">
<param name="ios-package" value="CDVWKWebViewEngine" />
</feature>
<preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
<platform name="android">
<preference name="android-minSdkVersion" value="26" />
<preference name="android-targetSdkVersion" value="26" />
<config-file parent="/*" target="app/src/main/AndroidManifest.xml">
<uses-permission android:name="android.permission.CAMERA" />
</config-file>
<config-file parent="/*" target="AndroidManifest.xml">
<uses-permission android:name="android.permission.CAMERA" />
</config-file>
</platform>
<platform name="ios">
<edit-config target="NSCameraUsageDescription" file="*-Info.plist" mode="merge">
<string>camera string.</string>
</edit-config>
<edit-config target="NSPhotoLibraryAddUsageDescription" file="*-Info.plist" mode="merge">
<string>camera string.</string>
</edit-config>
<edit-config target="NSPhotoLibraryUsageDescription" file="*-Info.plist" mode="merge">
<string>camera string.</string>
</edit-config>
</platform>
@janpio update on this since it was open?
from cordova-plugin-inappbrowser.
help! I have the same issue.
from cordova-plugin-inappbrowser.
I tried adding this code, but it has no effect. when clicking browse, it still shows the file manager. I don't have too much with android plugins. any ideas?
from cordova-plugin-inappbrowser.
now,I found another question,I has opened the camera,when i sure choose the picture,I get the imagePath in "callbackFromNative" method in MainActivity ,but not in inappbrowser. so I can't use the imagePath in the pages of inappbrowser.
from cordova-plugin-inappbrowser.
from cordova-plugin-inappbrowser.
To solve the permission's issue, go to App Configuration (configurations > apps > you app> permissions) and manually allow the permissions, and try again. If it works, the next step is change code to request permission automatically.
About erasing the image's files, probably it's possible. But I have no time yet to try this. But I'm sure that I gonna need it.
from cordova-plugin-inappbrowser.
were able to open the camera via the input file?
from cordova-plugin-inappbrowser.
Yes, through the input file, I was able to access the gallery and choose between image and camera, and take photo.
from cordova-plugin-inappbrowser.
Dude I could not through inappbrowser, could you send me the plugin file, to replace in my app? Here only opens the file explorer.
My email [email protected]
from cordova-plugin-inappbrowser.
Sorry, I don't have access to project anymore, but you can try the changes recommended on https://stackoverflow.com/questions/26381050/choose-camera-in-file-upload-in-cordova-application-on-android-without-using-cor/54425770#54425770 (at Jan 29 at 16:42)
from cordova-plugin-inappbrowser.
I've already changed that guy and keep opening only the file explorer, did you change it in plugins / inappbrowser? And which Android did you test is this solution?
from cordova-plugin-inappbrowser.
Yes, I downloaded the plugin version 3.0.0 from the plugin and changed the .java files that were in plugin's folder. The tests were performed on Android 7 and 8
from cordova-plugin-inappbrowser.
I am testing on android 5.1 and 6.0 here and it is not working. I'll test on Android 7 and 8 here. I made the modifications in the InAppBrowser.java file in the plugins / inappbrowser folder in ionic 3.
from cordova-plugin-inappbrowser.
I also tried on android 7 and 7.1 and continue to open only the file explorer, it does not open the camera.
from cordova-plugin-inappbrowser.
from cordova-plugin-inappbrowser.
Yes, I followed everything as stated above and in the post that you indicated me and when I click on some input file in the in app browser continues opening the file explorer.
from cordova-plugin-inappbrowser.
I still no solution here, man? Any suggestion? I have already tested on all android and continues to open the file explorer.
from cordova-plugin-inappbrowser.
Você executou o build? Talvez apagar toda a pasta platform e adicioná-la novamente funcione. se você alterou na pasta que indiquei, é possível que não tenha atualizado platform. Eu tenho certeza que isso funciona, implantei o sistema com isso há uns 3 meses. A versão do ionic 3, cordova 8.
from cordova-plugin-inappbrowser.
Você executou o build? Talvez apagar toda a pasta platform e adicioná-la novamente funcione. se você alterou na pasta que indiquei, é possível que não tenha atualizado platform. Eu tenho certeza que isso funciona, implantei o sistema com isso há uns 3 meses. A versão do ionic 3, cordova 8.
Dude I created a new project in ionic 3 using Cordova 8.1.2. I added the plugin inappbrowser using the command cordova ionic cordova plugin add cordova-plugin-inappbrowser and then added the modifications in the directory you indicated. I made the plugin call like this:
declare var cordova: any;
const browser = cordova.InAppBrowser.open ('link', '_ blank');
Then I ran the build and continued as if I had not inserted modifications to the plugin, same behavior opening the file explorer.
from cordova-plugin-inappbrowser.
Please, install [email protected] in you ionic app and replace the content file node_modules\cordova-plugin-inappbrowser\src\android\InAppBrowser.java with below code. Try app and give feeback, ok?
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova.inappbrowser; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Environment; import android.provider.Browser; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Color; import android.net.Uri; import android.os.Build; . . . . . . . . . . . . // WebView inAppWebView = new WebView(cordova.getActivity()); inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); inAppWebView.setId(Integer.valueOf(6)); // File Chooser Implemented ChromeClient inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView) { // For Android 5.0+ public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { if(Build.VERSION.SDK_INT >=23 && (cordova.getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || cordova.getActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) { cordova.getActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1); } LOG.d(LOG_TAG, "File Chooser 5.0+"); // If callback exists, finish it. if(mUploadCallbackLollipop != null) { mUploadCallbackLollipop.onReceiveValue(null); } mUploadCallbackLollipop = filePathCallback; Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); } // By default handle 401 like we'd normally do! super.onReceivedHttpAuthRequest(view, handler, host, realm); } } }
This worked for me.
After you have copied the file, you have to remove the android platform and add it again, then build and try :)
thanks a lot @gilbertogwa !
from cordova-plugin-inappbrowser.
Por favor, instale [email protected] em seu aplicativo iônico e substitua o arquivo de conteúdo node_modules \ cordova-plugin-inappbrowser \ src \ android \ InAppBrowser.java com o código abaixo. Tente app e dar feeback, ok?
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova.inappbrowser; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Environment; import android.provider.Browser; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.text.InputType; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.HttpAuthHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import org.apache.cordova.CallbackContext; import org.apache.cordova.Config; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaHttpAuthHandler; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.LOG; import org.apache.cordova.PluginManager; import org.apache.cordova.PluginResult; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.HashMap; import java.util.StringTokenizer; import java.util.Locale;; @SuppressLint("SetJavaScriptEnabled") public class InAppBrowser extends CordovaPlugin { private static final String NULL = "null"; protected static final String LOG_TAG = "InAppBrowser"; private static final String SELF = "_self"; private static final String SYSTEM = "_system"; private static final String EXIT_EVENT = "exit"; private static final String LOCATION = "location"; private static final String ZOOM = "zoom"; private static final String HIDDEN = "hidden"; private static final String LOAD_START_EVENT = "loadstart"; private static final String LOAD_STOP_EVENT = "loadstop"; private static final String LOAD_ERROR_EVENT = "loaderror"; private static final String CLEAR_ALL_CACHE = "clearcache"; private static final String CLEAR_SESSION_CACHE = "clearsessioncache"; private static final String HARDWARE_BACK_BUTTON = "hardwareback"; private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction"; private static final String SHOULD_PAUSE = "shouldPauseOnSuspend"; private static final Boolean DEFAULT_HARDWARE_BACK = true; private static final String USER_WIDE_VIEW_PORT = "useWideViewPort"; private static final String TOOLBAR_COLOR = "toolbarcolor"; private static final String CLOSE_BUTTON_CAPTION = "closebuttoncaption"; private static final String CLOSE_BUTTON_COLOR = "closebuttoncolor"; private static final String HIDE_NAVIGATION = "hidenavigationbuttons"; private static final String NAVIGATION_COLOR = "navigationbuttoncolor"; private static final String HIDE_URL = "hideurlbar"; private static final String FOOTER = "footer"; private static final String FOOTER_COLOR = "footercolor"; private static final List customizableOptions = Arrays.asList(CLOSE_BUTTON_CAPTION, TOOLBAR_COLOR, NAVIGATION_COLOR, CLOSE_BUTTON_COLOR, FOOTER_COLOR); private InAppBrowserDialog dialog; private WebView inAppWebView; private EditText edittext; private CallbackContext callbackContext; private boolean showLocationBar = true; private boolean showZoomControls = true; private boolean openWindowHidden = false; private boolean clearAllCache = false; private boolean clearSessionCache = false; private boolean hadwareBackButton = true; private boolean mediaPlaybackRequiresUserGesture = false; private boolean shouldPauseInAppBrowser = false; private boolean useWideViewPort = true; private ValueCallback<Uri> mUploadCallback; private ValueCallback<Uri[]> mUploadCallbackLollipop; private final static int FILECHOOSER_REQUESTCODE = 1; private final static int FILECHOOSER_REQUESTCODE_LOLLIPOP = 2; private String closeButtonCaption = ""; private String closeButtonColor = ""; private int toolbarColor = android.graphics.Color.LTGRAY; private boolean hideNavigationButtons = false; private String navigationButtonColor = ""; private boolean hideUrlBar = false; private boolean showFooter = false; private String footerColor = ""; private String[] allowedSchemes; private String mCM; /** * Executes the request and returns PluginResult. * * @param action the action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext the callbackContext used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { if (action.equals("open")) { this.callbackContext = callbackContext; final String url = args.getString(0); String t = args.optString(1); if (t == null || t.equals("") || t.equals(NULL)) { t = SELF; } final String target = t; final HashMap<String, String> features = parseFeature(args.optString(2)); LOG.d(LOG_TAG, "target = " + target); this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { String result = ""; // SELF if (SELF.equals(target)) { LOG.d(LOG_TAG, "in self"); /* This code exists for compatibility between 3.x and 4.x versions of Cordova. * Previously the Config class had a static method, isUrlWhitelisted(). That * responsibility has been moved to the plugins, with an aggregating method in * PluginManager. */ Boolean shouldAllowNavigation = null; if (url.startsWith("javascript:")) { shouldAllowNavigation = true; } if (shouldAllowNavigation == null) { try { Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class); shouldAllowNavigation = (Boolean)iuw.invoke(null, url); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } if (shouldAllowNavigation == null) { try { Method gpm = webView.getClass().getMethod("getPluginManager"); PluginManager pm = (PluginManager)gpm.invoke(webView); Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class); shouldAllowNavigation = (Boolean)san.invoke(pm, url); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } // load in webview if (Boolean.TRUE.equals(shouldAllowNavigation)) { LOG.d(LOG_TAG, "loading in webview"); webView.loadUrl(url); } //Load the dialer else if (url.startsWith(WebView.SCHEME_TEL)) { try { LOG.d(LOG_TAG, "loading in dialer"); Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } // load in InAppBrowser else { LOG.d(LOG_TAG, "loading in InAppBrowser"); result = showWebPage(url, features); } } // SYSTEM else if (SYSTEM.equals(target)) { LOG.d(LOG_TAG, "in system"); result = openExternal(url); } // BLANK - or anything else else { LOG.d(LOG_TAG, "in blank"); result = showWebPage(url, features); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } }); } else if (action.equals("close")) { closeDialog(); } else if (action.equals("injectScriptCode")) { String jsWrapper = null; if (args.getBoolean(1)) { jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId()); } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectScriptFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleCode")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("show")) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { dialog.show(); } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); } else if (action.equals("hide")) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { dialog.hide(); } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); } else { return false; } return true; } /** * Called when the view navigates. */ @Override public void onReset() { closeDialog(); } /** * Called when the system is about to start resuming a previous activity. */ @Override public void onPause(boolean multitasking) { if (shouldPauseInAppBrowser) { inAppWebView.onPause(); } } /** * Called when the activity will start interacting with the user. */ @Override public void onResume(boolean multitasking) { if (shouldPauseInAppBrowser) { inAppWebView.onResume(); } } /** * Called by AccelBroker when listener is to be shut down. * Stop listener. */ public void onDestroy() { closeDialog(); } /** * Inject an object (script or style) into the InAppBrowser WebView. * * This is a helper method for the inject{Script|Style}{Code|File} API calls, which * provides a consistent method for injecting JavaScript code into the document. * * If a wrapper string is supplied, then the source string will be JSON-encoded (adding * quotes) and wrapped using string formatting. (The wrapper string should have a single * '%s' marker) * * @param source The source object (filename or script/style text) to inject into * the document. * @param jsWrapper A JavaScript string to wrap the source string in, so that the object * is properly injected, or null if the source string is JavaScript text * which should be executed directly. */ private void injectDeferredObject(String source, String jsWrapper) { if (inAppWebView!=null) { String scriptToInject; if (jsWrapper != null) { org.json.JSONArray jsonEsc = new org.json.JSONArray(); jsonEsc.put(source); String jsonRepr = jsonEsc.toString(); String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1); scriptToInject = String.format(jsWrapper, jsonSourceString); } else { scriptToInject = source; } final String finalScriptToInject = scriptToInject; this.cordova.getActivity().runOnUiThread(new Runnable() { @SuppressLint("NewApi") @Override public void run() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // This action will have the side-effect of blurring the currently focused element inAppWebView.loadUrl("javascript:" + finalScriptToInject); } else { inAppWebView.evaluateJavascript(finalScriptToInject, null); } } }); } else { LOG.d(LOG_TAG, "Can't inject code into the system browser"); } } /** * Put the list of features into a hash map * * @param optString * @return */ private HashMap<String, String> parseFeature(String optString) { if (optString.equals(NULL)) { return null; } else { HashMap<String, String> map = new HashMap<String, String>(); StringTokenizer features = new StringTokenizer(optString, ","); StringTokenizer option; while(features.hasMoreElements()) { option = new StringTokenizer(features.nextToken(), "="); if (option.hasMoreElements()) { String key = option.nextToken(); String value = option.nextToken(); if (!customizableOptions.contains(key)){ value = value.equals("yes") || value.equals("no") ? value : "yes"; } map.put(key, value); } } return map; } } /** * Display a new browser with the specified URL. * * @param url the url to load. * @return "" if ok, or error message. */ public String openExternal(String url) { try { Intent intent = null; intent = new Intent(Intent.ACTION_VIEW); // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent". // Adding the MIME type to http: URLs causes them to not be handled by the downloader. Uri uri = Uri.parse(url); if ("file".equals(uri.getScheme())) { intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri)); } else { intent.setData(uri); } intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName()); this.cordova.getActivity().startActivity(intent); return ""; // not catching FileUriExposedException explicitly because buildtools<24 doesn't know about it } catch (java.lang.RuntimeException e) { LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString()); return e.toString(); } } /** * Closes the dialog */ public void closeDialog() { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { final WebView childView = inAppWebView; // The JS protects against multiple calls, so this should happen only when // closeDialog() is called by other native code. if (childView == null) { return; } childView.setWebViewClient(new WebViewClient() { // NB: wait for about:blank before dismissing public void onPageFinished(WebView view, String url) { if (dialog != null) { dialog.dismiss(); dialog = null; } } }); // NB: From SDK 19: "If you call methods on WebView from any thread // other than your app's UI thread, it can cause unexpected results." // http://developer.android.com/guide/webapps/migrating.html#Threads childView.loadUrl("about:blank"); try { JSONObject obj = new JSONObject(); obj.put("type", EXIT_EVENT); sendUpdate(obj, false); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } }); } /** * Checks to see if it is possible to go back one page in history, then does so. */ public void goBack() { if (this.inAppWebView.canGoBack()) { this.inAppWebView.goBack(); } } /** * Can the web browser go back? * @return boolean */ public boolean canGoBack() { return this.inAppWebView.canGoBack(); } /** * Has the user set the hardware back button to go back * @return boolean */ public boolean hardwareBack() { return hadwareBackButton; } /** * Checks to see if it is possible to go forward one page in history, then does so. */ private void goForward() { if (this.inAppWebView.canGoForward()) { this.inAppWebView.goForward(); } } /** * Navigate to the new page * * @param url to load */ private void navigate(String url) { InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0); if (!url.startsWith("http") && !url.startsWith("file:")) { this.inAppWebView.loadUrl("http://" + url); } else { this.inAppWebView.loadUrl(url); } this.inAppWebView.requestFocus(); } /** * Should we show the location bar? * * @return boolean */ private boolean getShowLocationBar() { return this.showLocationBar; } private InAppBrowser getInAppBrowser(){ return this; } /** * Display a new browser with the specified URL. * * @param url the url to load. * @param features jsonObject */ public String showWebPage(final String url, HashMap<String, String> features) { // Determine if we should hide the location bar. showLocationBar = true; showZoomControls = true; openWindowHidden = false; mediaPlaybackRequiresUserGesture = false; if (features != null) { String show = features.get(LOCATION); if (show != null) { showLocationBar = show.equals("yes") ? true : false; } if(showLocationBar) { String hideNavigation = features.get(HIDE_NAVIGATION); String hideUrl = features.get(HIDE_URL); if(hideNavigation != null) hideNavigationButtons = hideNavigation.equals("yes") ? true : false; if(hideUrl != null) hideUrlBar = hideUrl.equals("yes") ? true : false; } String zoom = features.get(ZOOM); if (zoom != null) { showZoomControls = zoom.equals("yes") ? true : false; } String hidden = features.get(HIDDEN); if (hidden != null) { openWindowHidden = hidden.equals("yes") ? true : false; } String hardwareBack = features.get(HARDWARE_BACK_BUTTON); if (hardwareBack != null) { hadwareBackButton = hardwareBack.equals("yes") ? true : false; } else { hadwareBackButton = DEFAULT_HARDWARE_BACK; } String mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION); if (mediaPlayback != null) { mediaPlaybackRequiresUserGesture = mediaPlayback.equals("yes") ? true : false; } String cache = features.get(CLEAR_ALL_CACHE); if (cache != null) { clearAllCache = cache.equals("yes") ? true : false; } else { cache = features.get(CLEAR_SESSION_CACHE); if (cache != null) { clearSessionCache = cache.equals("yes") ? true : false; } } String shouldPause = features.get(SHOULD_PAUSE); if (shouldPause != null) { shouldPauseInAppBrowser = shouldPause.equals("yes") ? true : false; } String wideViewPort = features.get(USER_WIDE_VIEW_PORT); if (wideViewPort != null ) { useWideViewPort = wideViewPort.equals("yes") ? true : false; } String closeButtonCaptionSet = features.get(CLOSE_BUTTON_CAPTION); if (closeButtonCaptionSet != null) { closeButtonCaption = closeButtonCaptionSet; } String closeButtonColorSet = features.get(CLOSE_BUTTON_COLOR); if (closeButtonColorSet != null) { closeButtonColor = closeButtonColorSet; } String toolbarColorSet = features.get(TOOLBAR_COLOR); if (toolbarColorSet != null) { toolbarColor = android.graphics.Color.parseColor(toolbarColorSet); } String navigationButtonColorSet = features.get(NAVIGATION_COLOR); if (navigationButtonColorSet != null) { navigationButtonColor = navigationButtonColorSet; } String showFooterSet = features.get(FOOTER); if (showFooterSet != null) { showFooter = showFooterSet.equals("yes") ? true : false; } String footerColorSet = features.get(FOOTER_COLOR); if (footerColorSet != null) { footerColor = footerColorSet; } } final CordovaWebView thatWebView = this.webView; // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics() ); return value; } private View createCloseButton(int id){ View _close; Resources activityRes = cordova.getActivity().getResources(); if (closeButtonCaption != "") { // Use TextView for text TextView close = new TextView(cordova.getActivity()); close.setText(closeButtonCaption); close.setTextSize(20); if (closeButtonColor != "") close.setTextColor(android.graphics.Color.parseColor(closeButtonColor)); close.setGravity(android.view.Gravity.CENTER_VERTICAL); close.setPadding(this.dpToPixels(10), 0, this.dpToPixels(10), 0); _close = close; } else { ImageButton close = new ImageButton(cordova.getActivity()); int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName()); Drawable closeIcon = activityRes.getDrawable(closeResId); if (closeButtonColor != "") close.setColorFilter(android.graphics.Color.parseColor(closeButtonColor)); close.setImageDrawable(closeIcon); close.setScaleType(ImageView.ScaleType.FIT_CENTER); if (Build.VERSION.SDK_INT >= 16) close.getAdjustViewBounds(); _close = close; } RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); _close.setLayoutParams(closeLayoutParams); if (Build.VERSION.SDK_INT >= 16) _close.setBackground(null); else _close.setBackgroundDrawable(null); _close.setContentDescription("Close Button"); _close.setId(Integer.valueOf(id)); _close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); return _close; } @SuppressLint("NewApi") public void run() { // CB-6702 InAppBrowser hangs when opening more than one instance if (dialog != null) { dialog.dismiss(); }; // Let's create the main dialog dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setInAppBroswer(getInAppBrowser()); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); //Please, no more black! toolbar.setBackgroundColor(toolbarColor); toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(Integer.valueOf(1)); // Back button ImageButton back = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(Integer.valueOf(2)); Resources activityRes = cordova.getActivity().getResources(); int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName()); Drawable backIcon = activityRes.getDrawable(backResId); if (navigationButtonColor != "") back.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor)); if (Build.VERSION.SDK_INT >= 16) back.setBackground(null); else back.setBackgroundDrawable(null); back.setImageDrawable(backIcon); back.setScaleType(ImageView.ScaleType.FIT_CENTER); back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) back.getAdjustViewBounds(); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button ImageButton forward = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(Integer.valueOf(3)); int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName()); Drawable fwdIcon = activityRes.getDrawable(fwdResId); if (navigationButtonColor != "") forward.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor)); if (Build.VERSION.SDK_INT >= 16) forward.setBackground(null); else forward.setBackgroundDrawable(null); forward.setImageDrawable(fwdIcon); forward.setScaleType(ImageView.ScaleType.FIT_CENTER); forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) forward.getAdjustViewBounds(); forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(Integer.valueOf(4)); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Header Close/Done button View close = createCloseButton(5); toolbar.addView(close); // Footer RelativeLayout footer = new RelativeLayout(cordova.getActivity()); int _footerColor; if(footerColor != ""){ _footerColor = Color.parseColor(footerColor); }else{ _footerColor = android.graphics.Color.LTGRAY; } footer.setBackgroundColor(_footerColor); RelativeLayout.LayoutParams footerLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)); footerLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); footer.setLayoutParams(footerLayout); if (closeButtonCaption != "") footer.setPadding(this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8)); footer.setHorizontalGravity(Gravity.LEFT); footer.setVerticalGravity(Gravity.BOTTOM); View footerClose = createCloseButton(7); footer.addView(footerClose); // WebView inAppWebView = new WebView(cordova.getActivity()); inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); inAppWebView.setId(Integer.valueOf(6)); // File Chooser Implemented ChromeClient inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView) { // For Android 5.0+ public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { if(Build.VERSION.SDK_INT >=23 && (cordova.getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || cordova.getActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) { cordova.getActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1); } LOG.d(LOG_TAG, "File Chooser 5.0+"); // If callback exists, finish it. if(mUploadCallbackLollipop != null) { mUploadCallbackLollipop.onReceiveValue(null); } mUploadCallbackLollipop = filePathCallback; Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(takePictureIntent.resolveActivity(cordova.getActivity().getPackageManager()) != null) { File photoFile = null; try{ photoFile = createImageFile(); takePictureIntent.putExtra("PhotoPath", mCM); }catch(IOException ex){ Log.e(LOG_TAG, "Image file creation failed", ex); } if(photoFile != null){ mCM = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); }else{ takePictureIntent = null; } } // Create File Chooser Intent Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType("*/*"); Intent[] intentArray; if(takePictureIntent != null){ intentArray = new Intent[]{takePictureIntent}; }else{ intentArray = new Intent[0]; } Locale localeInfo = cordova.getActivity().getApplicationContext().getResources() .getConfiguration().getLocales().get(0); String lang = localeInfo.toLanguageTag(); String title; if (lang.startsWith("en")) { title = "Choose the source"; } else if (lang.startsWith("es")) { title = "Seleccione el origen"; } else { title = "Escolha a origem"; } Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, title); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); // Run cordova startActivityForResult cordova.startActivityForResult(InAppBrowser.this, chooserIntent, FILECHOOSER_REQUESTCODE); return true; } // For Android 4.1+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { LOG.d(LOG_TAG, "File Chooser 4.1+"); // Call file chooser for Android 3.0+ openFileChooser(uploadMsg, acceptType); } // For Android 3.0+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { LOG.d(LOG_TAG, "File Chooser 3.0+"); mUploadCallback = uploadMsg; Intent content = new Intent(Intent.ACTION_GET_CONTENT); content.addCategory(Intent.CATEGORY_OPENABLE); // run startActivityForResult cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE); } }); WebViewClient client = new InAppBrowserClient(thatWebView, edittext); inAppWebView.setWebViewClient(client); WebSettings settings = inAppWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(showZoomControls); settings.setPluginState(android.webkit.WebSettings.PluginState.ON); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture); } String overrideUserAgent = preferences.getString("OverrideUserAgent", null); String appendUserAgent = preferences.getString("AppendUserAgent", null); if (overrideUserAgent != null) { settings.setUserAgentString(overrideUserAgent); } if (appendUserAgent != null) { settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent); } //Toggle whether this is enabled or not! Bundle appSettings = cordova.getActivity().getIntent().getExtras(); boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true); if (enableDatabase) { String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); settings.setDatabaseEnabled(true); } settings.setDomStorageEnabled(true); if (clearAllCache) { CookieManager.getInstance().removeAllCookie(); } else if (clearSessionCache) { CookieManager.getInstance().removeSessionCookie(); } // Enable Thirdparty Cookies on >=Android 5.0 device if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().setAcceptThirdPartyCookies(inAppWebView,true); } inAppWebView.loadUrl(url); inAppWebView.setId(Integer.valueOf(6)); inAppWebView.getSettings().setLoadWithOverviewMode(true); inAppWebView.getSettings().setUseWideViewPort(useWideViewPort); inAppWebView.requestFocus(); inAppWebView.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar if they haven't been disabled if (!hideNavigationButtons) toolbar.addView(actionButtonContainer); if (!hideUrlBar) toolbar.addView(edittext); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout RelativeLayout webViewLayout = new RelativeLayout(cordova.getActivity()); webViewLayout.addView(inAppWebView); main.addView(webViewLayout); // Don't add the footer unless it's been enabled if (showFooter) { webViewLayout.addView(footer); } WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); // the goal of openhidden is to load the url and not display it // Show() needs to be called to cause the URL to be loaded if(openWindowHidden) { dialog.hide(); } } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; } private File createImageFile() throws IOException{ @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "img_"+timeStamp+"_"; File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); return File.createTempFile(imageFileName,".jpg",storageDir); } /** * Create a new plugin success result and send it back to JavaScript * * @param obj a JSONObject contain event payload information */ private void sendUpdate(JSONObject obj, boolean keepCallback) { sendUpdate(obj, keepCallback, PluginResult.Status.OK); } /** * Create a new plugin result and send it back to JavaScript * * @param obj a JSONObject contain event payload information * @param status the status code to return to the JavaScript environment */ private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) { if (callbackContext != null) { PluginResult result = new PluginResult(status, obj); result.setKeepCallback(keepCallback); callbackContext.sendPluginResult(result); if (!keepCallback) { callbackContext = null; } } } /** * Receive File Data from File Chooser * * @param requestCode the requested code from chromeclient * @param resultCode the result code returned from android system * @param intent the data from android file chooser */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // For Android >= 5.0 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LOG.d(LOG_TAG, "onActivityResult (For Android >= 5.0)"); Uri[] results = null; //Check if response is positive if(resultCode== Activity.RESULT_OK){ if(requestCode == FILECHOOSER_REQUESTCODE){ if(null == mUploadCallbackLollipop){ return; } if(intent == null || intent.getData() == null){ //Capture Photo if no image available if(mCM != null){ results = new Uri[]{Uri.parse(mCM)}; } }else{ String dataString = intent.getDataString(); if(dataString != null){ results = new Uri[]{Uri.parse(dataString)}; } } } } mUploadCallbackLollipop .onReceiveValue(results); mUploadCallbackLollipop = null; } // For Android < 5.0 else { LOG.d(LOG_TAG, "onActivityResult (For Android < 5.0)"); // If RequestCode or Callback is Invalid if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) { super.onActivityResult(requestCode, resultCode, intent); return; } if (null == mUploadCallback) return; Uri result = intent == null || resultCode != cordova.getActivity().RESULT_OK ? null : intent.getData(); mUploadCallback.onReceiveValue(result); mUploadCallback = null; } } /** * The webview client receives notifications about appView */ public class InAppBrowserClient extends WebViewClient { EditText edittext; CordovaWebView webView; /** * Constructor. * * @param webView * @param mEditText */ public InAppBrowserClient(CordovaWebView webView, EditText mEditText) { this.webView = webView; this.edittext = mEditText; } /** * Override the URL that should be loaded * * This handles a small subset of all the URIs that would be encountered. * * @param webView * @param url */ @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:" + address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString()); } } // Test for whitelisted custom scheme names like mycoolapp:// or twitteroauthresponse:// (Twitter Oauth Response) else if (!url.startsWith("http:") && !url.startsWith("https:") && url.matches("^[a-z]*://.*?$")) { if (allowedSchemes == null) { String allowed = preferences.getString("AllowedSchemes", ""); allowedSchemes = allowed.split(","); } if (allowedSchemes != null) { for (String scheme : allowedSchemes) { if (url.startsWith(scheme)) { try { JSONObject obj = new JSONObject(); obj.put("type", "customscheme"); obj.put("url", url); sendUpdate(obj, true); return true; } catch (JSONException ex) { LOG.e(LOG_TAG, "Custom Scheme URI passed in has caused a JSON error."); } } } } } return false; } /* * onPageStarted fires the LOAD_START_EVENT * * @param view * @param url * @param favicon */ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); String newloc = ""; if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) { newloc = url; } else { // Assume that everything is HTTP at this point, because if we don't specify, // it really should be. Complain loudly about this!!! LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI"); newloc = "http://" + url; } // Update the UI if we haven't already if (!newloc.equals(edittext.getText().toString())) { edittext.setText(newloc); } try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_START_EVENT); obj.put("url", newloc); sendUpdate(obj, true); } catch (JSONException ex) { LOG.e(LOG_TAG, "URI passed in has caused a JSON error."); } } public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().flush(); } else { CookieSyncManager.getInstance().sync(); } // https://issues.apache.org/jira/browse/CB-11248 view.clearFocus(); view.requestFocus(); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_STOP_EVENT); obj.put("url", url); sendUpdate(obj, true); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_ERROR_EVENT); obj.put("url", failingUrl); obj.put("code", errorCode); obj.put("message", description); sendUpdate(obj, true, PluginResult.Status.ERROR); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } /** * On received http auth request. */ @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // Check if there is some plugin which can resolve this auth challenge PluginManager pluginManager = null; try { Method gpm = webView.getClass().getMethod("getPluginManager"); pluginManager = (PluginManager)gpm.invoke(webView); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } if (pluginManager == null) { try { Field pmf = webView.getClass().getField("pluginManager"); pluginManager = (PluginManager)pmf.get(webView); } catch (NoSuchFieldException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) { return; } // By default handle 401 like we'd normally do! super.onReceivedHttpAuthRequest(view, handler, host, realm); } } }
This worked for me.
After inserting the modifications as indicated in issue in the java InAppBrowser.java file in / plugins / cordova-plugin-inappbrowser / src / android I removed the folder platform and www and inserted again and the modifications appeared effect and appeared the camera.
Thanks a lot @gilbertogwa !
from cordova-plugin-inappbrowser.
This is great! But what exactly was the actual fix inside of this code @gilbertogwa ? Was it a couple of lines fix or there were a multitude of updates?
from cordova-plugin-inappbrowser.
This is great! But what exactly was the actual fix @gilbertogwa ?
Please, install [email protected] in you ionic app and replace the content file plugins\cordova-plugin-inappbrowser\src\android\InAppBrowser.java with below code. Try app and give feeback, ok?
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.inappbrowser;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.provider.Browser;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
.
.
.
.
.
.
.
.
.
.
.
.
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));
// File Chooser Implemented ChromeClient
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView) {
// For Android 5.0+
public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if(Build.VERSION.SDK_INT >=23 && (cordova.getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || cordova.getActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
cordova.getActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
LOG.d(LOG_TAG, "File Chooser 5.0+");
// If callback exists, finish it.
if(mUploadCallbackLollipop != null) {
mUploadCallbackLollipop.onReceiveValue(null);
}
mUploadCallbackLollipop = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
}
// By default handle 401 like we'd normally do!
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
}
This worked for me.
After you have copied the file, you have to remove the android platform and add it again, then build and try :)
thanks a lot @gilbertogwa !
jeffersonveloso commented 4 hours ago
Por favor, instale [email protected] em seu aplicativo iônico e substitua o arquivo de conteúdo node_modules \ cordova-plugin-inappbrowser \ src \ android \ InAppBrowser.java com o código abaixo. Tente app e dar feeback, ok?
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.inappbrowser;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.provider.Browser;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaHttpAuthHandler;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginManager;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Locale;;
@SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private static final String NULL = "null";
protected static final String LOG_TAG = "InAppBrowser";
private static final String SELF = "_self";
private static final String SYSTEM = "_system";
private static final String EXIT_EVENT = "exit";
private static final String LOCATION = "location";
private static final String ZOOM = "zoom";
private static final String HIDDEN = "hidden";
private static final String LOAD_START_EVENT = "loadstart";
private static final String LOAD_STOP_EVENT = "loadstop";
private static final String LOAD_ERROR_EVENT = "loaderror";
private static final String CLEAR_ALL_CACHE = "clearcache";
private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
private static final String HARDWARE_BACK_BUTTON = "hardwareback";
private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction";
private static final String SHOULD_PAUSE = "shouldPauseOnSuspend";
private static final Boolean DEFAULT_HARDWARE_BACK = true;
private static final String USER_WIDE_VIEW_PORT = "useWideViewPort";
private static final String TOOLBAR_COLOR = "toolbarcolor";
private static final String CLOSE_BUTTON_CAPTION = "closebuttoncaption";
private static final String CLOSE_BUTTON_COLOR = "closebuttoncolor";
private static final String HIDE_NAVIGATION = "hidenavigationbuttons";
private static final String NAVIGATION_COLOR = "navigationbuttoncolor";
private static final String HIDE_URL = "hideurlbar";
private static final String FOOTER = "footer";
private static final String FOOTER_COLOR = "footercolor";
private static final List customizableOptions = Arrays.asList(CLOSE_BUTTON_CAPTION, TOOLBAR_COLOR, NAVIGATION_COLOR, CLOSE_BUTTON_COLOR, FOOTER_COLOR);
private InAppBrowserDialog dialog;
private WebView inAppWebView;
private EditText edittext;
private CallbackContext callbackContext;
private boolean showLocationBar = true;
private boolean showZoomControls = true;
private boolean openWindowHidden = false;
private boolean clearAllCache = false;
private boolean clearSessionCache = false;
private boolean hadwareBackButton = true;
private boolean mediaPlaybackRequiresUserGesture = false;
private boolean shouldPauseInAppBrowser = false;
private boolean useWideViewPort = true;
private ValueCallback<Uri> mUploadCallback;
private ValueCallback<Uri[]> mUploadCallbackLollipop;
private final static int FILECHOOSER_REQUESTCODE = 1;
private final static int FILECHOOSER_REQUESTCODE_LOLLIPOP = 2;
private String closeButtonCaption = "";
private String closeButtonColor = "";
private int toolbarColor = android.graphics.Color.LTGRAY;
private boolean hideNavigationButtons = false;
private String navigationButtonColor = "";
private boolean hideUrlBar = false;
private boolean showFooter = false;
private String footerColor = "";
private String[] allowedSchemes;
private String mCM;
/**
* Executes the request and returns PluginResult.
*
* @param action the action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext the callbackContext used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("open")) {
this.callbackContext = callbackContext;
final String url = args.getString(0);
String t = args.optString(1);
if (t == null || t.equals("") || t.equals(NULL)) {
t = SELF;
}
final String target = t;
final HashMap<String, String> features = parseFeature(args.optString(2));
LOG.d(LOG_TAG, "target = " + target);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String result = "";
// SELF
if (SELF.equals(target)) {
LOG.d(LOG_TAG, "in self");
/* This code exists for compatibility between 3.x and 4.x versions of Cordova.
* Previously the Config class had a static method, isUrlWhitelisted(). That
* responsibility has been moved to the plugins, with an aggregating method in
* PluginManager.
*/
Boolean shouldAllowNavigation = null;
if (url.startsWith("javascript:")) {
shouldAllowNavigation = true;
}
if (shouldAllowNavigation == null) {
try {
Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
shouldAllowNavigation = (Boolean)iuw.invoke(null, url);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
if (shouldAllowNavigation == null) {
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
PluginManager pm = (PluginManager)gpm.invoke(webView);
Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
shouldAllowNavigation = (Boolean)san.invoke(pm, url);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
// load in webview
if (Boolean.TRUE.equals(shouldAllowNavigation)) {
LOG.d(LOG_TAG, "loading in webview");
webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.SCHEME_TEL))
{
try {
LOG.d(LOG_TAG, "loading in dialer");
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
// load in InAppBrowser
else {
LOG.d(LOG_TAG, "loading in InAppBrowser");
result = showWebPage(url, features);
}
}
// SYSTEM
else if (SYSTEM.equals(target)) {
LOG.d(LOG_TAG, "in system");
result = openExternal(url);
}
// BLANK - or anything else
else {
LOG.d(LOG_TAG, "in blank");
result = showWebPage(url, features);
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
});
}
else if (action.equals("close")) {
closeDialog();
}
else if (action.equals("injectScriptCode")) {
String jsWrapper = null;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId());
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectScriptFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleCode")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("show")) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.show();
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
else if (action.equals("hide")) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.hide();
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
else {
return false;
}
return true;
}
/**
* Called when the view navigates.
*/
@Override
public void onReset() {
closeDialog();
}
/**
* Called when the system is about to start resuming a previous activity.
*/
@Override
public void onPause(boolean multitasking) {
if (shouldPauseInAppBrowser) {
inAppWebView.onPause();
}
}
/**
* Called when the activity will start interacting with the user.
*/
@Override
public void onResume(boolean multitasking) {
if (shouldPauseInAppBrowser) {
inAppWebView.onResume();
}
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
closeDialog();
}
/**
* Inject an object (script or style) into the InAppBrowser WebView.
*
* This is a helper method for the inject{Script|Style}{Code|File} API calls, which
* provides a consistent method for injecting JavaScript code into the document.
*
* If a wrapper string is supplied, then the source string will be JSON-encoded (adding
* quotes) and wrapped using string formatting. (The wrapper string should have a single
* '%s' marker)
*
* @param source The source object (filename or script/style text) to inject into
* the document.
* @param jsWrapper A JavaScript string to wrap the source string in, so that the object
* is properly injected, or null if the source string is JavaScript text
* which should be executed directly.
*/
private void injectDeferredObject(String source, String jsWrapper) {
if (inAppWebView!=null) {
String scriptToInject;
if (jsWrapper != null) {
org.json.JSONArray jsonEsc = new org.json.JSONArray();
jsonEsc.put(source);
String jsonRepr = jsonEsc.toString();
String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1);
scriptToInject = String.format(jsWrapper, jsonSourceString);
} else {
scriptToInject = source;
}
final String finalScriptToInject = scriptToInject;
this.cordova.getActivity().runOnUiThread(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
// This action will have the side-effect of blurring the currently focused element
inAppWebView.loadUrl("javascript:" + finalScriptToInject);
} else {
inAppWebView.evaluateJavascript(finalScriptToInject, null);
}
}
});
} else {
LOG.d(LOG_TAG, "Can't inject code into the system browser");
}
}
/**
* Put the list of features into a hash map
*
* @param optString
* @return
*/
private HashMap<String, String> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, String> map = new HashMap<String, String>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
String value = option.nextToken();
if (!customizableOptions.contains(key)){
value = value.equals("yes") || value.equals("no") ? value : "yes";
}
map.put(key, value);
}
}
return map;
}
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @return "" if ok, or error message.
*/
public String openExternal(String url) {
try {
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW);
// Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
// Adding the MIME type to http: URLs causes them to not be handled by the downloader.
Uri uri = Uri.parse(url);
if ("file".equals(uri.getScheme())) {
intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri));
} else {
intent.setData(uri);
}
intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName());
this.cordova.getActivity().startActivity(intent);
return "";
// not catching FileUriExposedException explicitly because buildtools<24 doesn't know about it
} catch (java.lang.RuntimeException e) {
LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString());
return e.toString();
}
}
/**
* Closes the dialog
*/
public void closeDialog() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final WebView childView = inAppWebView;
// The JS protects against multiple calls, so this should happen only when
// closeDialog() is called by other native code.
if (childView == null) {
return;
}
childView.setWebViewClient(new WebViewClient() {
// NB: wait for about:blank before dismissing
public void onPageFinished(WebView view, String url) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
});
// NB: From SDK 19: "If you call methods on WebView from any thread
// other than your app's UI thread, it can cause unexpected results."
// http://developer.android.com/guide/webapps/migrating.html#Threads
childView.loadUrl("about:blank");
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
public void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
/**
* Can the web browser go back?
* @return boolean
*/
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
/**
* Has the user set the hardware back button to go back
* @return boolean
*/
public boolean hardwareBack() {
return hadwareBackButton;
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.inAppWebView.canGoForward()) {
this.inAppWebView.goForward();
}
}
/**
* Navigate to the new page
*
* @param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.inAppWebView.loadUrl("http://" + url);
} else {
this.inAppWebView.loadUrl(url);
}
this.inAppWebView.requestFocus();
}
/**
* Should we show the location bar?
*
* @return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
private InAppBrowser getInAppBrowser(){
return this;
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @param features jsonObject
*/
public String showWebPage(final String url, HashMap<String, String> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
openWindowHidden = false;
mediaPlaybackRequiresUserGesture = false;
if (features != null) {
String show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.equals("yes") ? true : false;
}
if(showLocationBar) {
String hideNavigation = features.get(HIDE_NAVIGATION);
String hideUrl = features.get(HIDE_URL);
if(hideNavigation != null) hideNavigationButtons = hideNavigation.equals("yes") ? true : false;
if(hideUrl != null) hideUrlBar = hideUrl.equals("yes") ? true : false;
}
String zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.equals("yes") ? true : false;
}
String hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.equals("yes") ? true : false;
}
String hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.equals("yes") ? true : false;
} else {
hadwareBackButton = DEFAULT_HARDWARE_BACK;
}
String mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION);
if (mediaPlayback != null) {
mediaPlaybackRequiresUserGesture = mediaPlayback.equals("yes") ? true : false;
}
String cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.equals("yes") ? true : false;
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.equals("yes") ? true : false;
}
}
String shouldPause = features.get(SHOULD_PAUSE);
if (shouldPause != null) {
shouldPauseInAppBrowser = shouldPause.equals("yes") ? true : false;
}
String wideViewPort = features.get(USER_WIDE_VIEW_PORT);
if (wideViewPort != null ) {
useWideViewPort = wideViewPort.equals("yes") ? true : false;
}
String closeButtonCaptionSet = features.get(CLOSE_BUTTON_CAPTION);
if (closeButtonCaptionSet != null) {
closeButtonCaption = closeButtonCaptionSet;
}
String closeButtonColorSet = features.get(CLOSE_BUTTON_COLOR);
if (closeButtonColorSet != null) {
closeButtonColor = closeButtonColorSet;
}
String toolbarColorSet = features.get(TOOLBAR_COLOR);
if (toolbarColorSet != null) {
toolbarColor = android.graphics.Color.parseColor(toolbarColorSet);
}
String navigationButtonColorSet = features.get(NAVIGATION_COLOR);
if (navigationButtonColorSet != null) {
navigationButtonColor = navigationButtonColorSet;
}
String showFooterSet = features.get(FOOTER);
if (showFooterSet != null) {
showFooter = showFooterSet.equals("yes") ? true : false;
}
String footerColorSet = features.get(FOOTER_COLOR);
if (footerColorSet != null) {
footerColor = footerColorSet;
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
private View createCloseButton(int id){
View _close;
Resources activityRes = cordova.getActivity().getResources();
if (closeButtonCaption != "") {
// Use TextView for text
TextView close = new TextView(cordova.getActivity());
close.setText(closeButtonCaption);
close.setTextSize(20);
if (closeButtonColor != "") close.setTextColor(android.graphics.Color.parseColor(closeButtonColor));
close.setGravity(android.view.Gravity.CENTER_VERTICAL);
close.setPadding(this.dpToPixels(10), 0, this.dpToPixels(10), 0);
_close = close;
}
else {
ImageButton close = new ImageButton(cordova.getActivity());
int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
Drawable closeIcon = activityRes.getDrawable(closeResId);
if (closeButtonColor != "") close.setColorFilter(android.graphics.Color.parseColor(closeButtonColor));
close.setImageDrawable(closeIcon);
close.setScaleType(ImageView.ScaleType.FIT_CENTER);
if (Build.VERSION.SDK_INT >= 16)
close.getAdjustViewBounds();
_close = close;
}
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
_close.setLayoutParams(closeLayoutParams);
if (Build.VERSION.SDK_INT >= 16)
_close.setBackground(null);
else
_close.setBackgroundDrawable(null);
_close.setContentDescription("Close Button");
_close.setId(Integer.valueOf(id));
_close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
return _close;
}
@SuppressLint("NewApi")
public void run() {
// CB-6702 InAppBrowser hangs when opening more than one instance
if (dialog != null) {
dialog.dismiss();
};
// Let's create the main dialog
dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setInAppBroswer(getInAppBrowser());
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
//Please, no more black!
toolbar.setBackgroundColor(toolbarColor);
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(Integer.valueOf(1));
// Back button
ImageButton back = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(Integer.valueOf(2));
Resources activityRes = cordova.getActivity().getResources();
int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
Drawable backIcon = activityRes.getDrawable(backResId);
if (navigationButtonColor != "") back.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
if (Build.VERSION.SDK_INT >= 16)
back.setBackground(null);
else
back.setBackgroundDrawable(null);
back.setImageDrawable(backIcon);
back.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
back.getAdjustViewBounds();
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
ImageButton forward = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(Integer.valueOf(3));
int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
Drawable fwdIcon = activityRes.getDrawable(fwdResId);
if (navigationButtonColor != "") forward.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
if (Build.VERSION.SDK_INT >= 16)
forward.setBackground(null);
else
forward.setBackgroundDrawable(null);
forward.setImageDrawable(fwdIcon);
forward.setScaleType(ImageView.ScaleType.FIT_CENTER);
forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
forward.getAdjustViewBounds();
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(Integer.valueOf(4));
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Header Close/Done button
View close = createCloseButton(5);
toolbar.addView(close);
// Footer
RelativeLayout footer = new RelativeLayout(cordova.getActivity());
int _footerColor;
if(footerColor != ""){
_footerColor = Color.parseColor(footerColor);
}else{
_footerColor = android.graphics.Color.LTGRAY;
}
footer.setBackgroundColor(_footerColor);
RelativeLayout.LayoutParams footerLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44));
footerLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
footer.setLayoutParams(footerLayout);
if (closeButtonCaption != "") footer.setPadding(this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8));
footer.setHorizontalGravity(Gravity.LEFT);
footer.setVerticalGravity(Gravity.BOTTOM);
View footerClose = createCloseButton(7);
footer.addView(footerClose);
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));
// File Chooser Implemented ChromeClient
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView) {
// For Android 5.0+
public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if(Build.VERSION.SDK_INT >=23 && (cordova.getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || cordova.getActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
cordova.getActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
LOG.d(LOG_TAG, "File Chooser 5.0+");
// If callback exists, finish it.
if(mUploadCallbackLollipop != null) {
mUploadCallbackLollipop.onReceiveValue(null);
}
mUploadCallbackLollipop = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(cordova.getActivity().getPackageManager()) != null) {
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(LOG_TAG, "Image file creation failed", ex);
}
if(photoFile != null){
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
}else{
takePictureIntent = null;
}
}
// Create File Chooser Intent
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if(takePictureIntent != null){
intentArray = new Intent[]{takePictureIntent};
}else{
intentArray = new Intent[0];
}
Locale localeInfo = cordova.getActivity().getApplicationContext().getResources()
.getConfiguration().getLocales().get(0);
String lang = localeInfo.toLanguageTag();
String title;
if (lang.startsWith("en"))
{
title = "Choose the source";
} else if (lang.startsWith("es"))
{
title = "Seleccione el origen";
} else
{
title = "Escolha a origem";
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, title);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
// Run cordova startActivityForResult
cordova.startActivityForResult(InAppBrowser.this, chooserIntent, FILECHOOSER_REQUESTCODE);
return true;
}
// For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
LOG.d(LOG_TAG, "File Chooser 4.1+");
// Call file chooser for Android 3.0+
openFileChooser(uploadMsg, acceptType);
}
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType)
{
LOG.d(LOG_TAG, "File Chooser 3.0+");
mUploadCallback = uploadMsg;
Intent content = new Intent(Intent.ACTION_GET_CONTENT);
content.addCategory(Intent.CATEGORY_OPENABLE);
// run startActivityForResult
cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE);
}
});
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(showZoomControls);
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
}
String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
String appendUserAgent = preferences.getString("AppendUserAgent", null);
if (overrideUserAgent != null) {
settings.setUserAgentString(overrideUserAgent);
}
if (appendUserAgent != null) {
settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent);
}
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if (enableDatabase) {
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
if (clearAllCache) {
CookieManager.getInstance().removeAllCookie();
} else if (clearSessionCache) {
CookieManager.getInstance().removeSessionCookie();
}
// Enable Thirdparty Cookies on >=Android 5.0 device
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(inAppWebView,true);
}
inAppWebView.loadUrl(url);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(useWideViewPort);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar if they haven't been disabled
if (!hideNavigationButtons) toolbar.addView(actionButtonContainer);
if (!hideUrlBar) toolbar.addView(edittext);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
RelativeLayout webViewLayout = new RelativeLayout(cordova.getActivity());
webViewLayout.addView(inAppWebView);
main.addView(webViewLayout);
// Don't add the footer unless it's been enabled
if (showFooter) {
webViewLayout.addView(footer);
}
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
// the goal of openhidden is to load the url and not display it
// Show() needs to be called to cause the URL to be loaded
if(openWindowHidden) {
dialog.hide();
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
private File createImageFile() throws IOException{
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
/**
* Create a new plugin success result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
*/
private void sendUpdate(JSONObject obj, boolean keepCallback) {
sendUpdate(obj, keepCallback, PluginResult.Status.OK);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
* @param status the status code to return to the JavaScript environment
*/
private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
if (callbackContext != null) {
PluginResult result = new PluginResult(status, obj);
result.setKeepCallback(keepCallback);
callbackContext.sendPluginResult(result);
if (!keepCallback) {
callbackContext = null;
}
}
}
/**
* Receive File Data from File Chooser
*
* @param requestCode the requested code from chromeclient
* @param resultCode the result code returned from android system
* @param intent the data from android file chooser
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// For Android >= 5.0
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
LOG.d(LOG_TAG, "onActivityResult (For Android >= 5.0)");
Uri[] results = null;
//Check if response is positive
if(resultCode== Activity.RESULT_OK){
if(requestCode == FILECHOOSER_REQUESTCODE){
if(null == mUploadCallbackLollipop){
return;
}
if(intent == null || intent.getData() == null){
//Capture Photo if no image available
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = intent.getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUploadCallbackLollipop .onReceiveValue(results);
mUploadCallbackLollipop = null;
}
// For Android < 5.0
else {
LOG.d(LOG_TAG, "onActivityResult (For Android < 5.0)");
// If RequestCode or Callback is Invalid
if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) {
super.onActivityResult(requestCode, resultCode, intent);
return;
}
if (null == mUploadCallback) return;
Uri result = intent == null || resultCode != cordova.getActivity().RESULT_OK ? null : intent.getData();
mUploadCallback.onReceiveValue(result);
mUploadCallback = null;
}
}
/**
* The webview client receives notifications about appView
*/
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
/**
* Constructor.
*
* @param webView
* @param mEditText
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
this.webView = webView;
this.edittext = mEditText;
}
/**
* Override the URL that should be loaded
*
* This handles a small subset of all the URIs that would be encountered.
*
* @param webView
* @param url
*/
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
} else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
} else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:" + address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
// Test for whitelisted custom scheme names like mycoolapp:// or twitteroauthresponse:// (Twitter Oauth Response)
else if (!url.startsWith("http:") && !url.startsWith("https:") && url.matches("^[a-z]*://.*?$")) {
if (allowedSchemes == null) {
String allowed = preferences.getString("AllowedSchemes", "");
allowedSchemes = allowed.split(",");
}
if (allowedSchemes != null) {
for (String scheme : allowedSchemes) {
if (url.startsWith(scheme)) {
try {
JSONObject obj = new JSONObject();
obj.put("type", "customscheme");
obj.put("url", url);
sendUpdate(obj, true);
return true;
} catch (JSONException ex) {
LOG.e(LOG_TAG, "Custom Scheme URI passed in has caused a JSON error.");
}
}
}
}
}
return false;
}
/*
* onPageStarted fires the LOAD_START_EVENT
*
* @param view
* @param url
* @param favicon
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc = "";
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
}
else
{
// Assume that everything is HTTP at this point, because if we don't specify,
// it really should be. Complain loudly about this!!!
LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI");
newloc = "http://" + url;
}
// Update the UI if we haven't already
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_START_EVENT);
obj.put("url", newloc);
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
}
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush();
} else {
CookieSyncManager.getInstance().sync();
}
// https://issues.apache.org/jira/browse/CB-11248
view.clearFocus();
view.requestFocus();
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
obj.put("url", url);
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", failingUrl);
obj.put("code", errorCode);
obj.put("message", description);
sendUpdate(obj, true, PluginResult.Status.ERROR);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
/**
* On received http auth request.
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
// Check if there is some plugin which can resolve this auth challenge
PluginManager pluginManager = null;
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
pluginManager = (PluginManager)gpm.invoke(webView);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
if (pluginManager == null) {
try {
Field pmf = webView.getClass().getField("pluginManager");
pluginManager = (PluginManager)pmf.get(webView);
} catch (NoSuchFieldException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) {
return;
}
// By default handle 401 like we'd normally do!
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
}
from cordova-plugin-inappbrowser.
Thanks @jeffersonveloso I just wanted to know what specifically in this code fixed the issue instead of just blindly copying and pasting it.
from cordova-plugin-inappbrowser.
@vsharp the secret is in method onShowFileChooser, because it is where the click action is being captured.
from cordova-plugin-inappbrowser.
Thanks @jeffersonveloso I just wanted to know what specifically in this code fixed the issue instead of just blindly copying and pasting it.
What he did was create the intention of the camera in this stretch.
if(mUploadCallbackLollipop != null) {
mUploadCallbackLollipop.onReceiveValue(null);
}
mUploadCallbackLollipop = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(cordova.getActivity().getPackageManager()) != null) {
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(LOG_TAG, "Image file creation failed", ex);
}
LOG.d(LOG_TAG, "TAKEPICTUREINTENT" + takePictureIntent);
LOG.d(LOG_TAG, "photoFile" + photoFile);
if(photoFile != null){
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
}else{
takePictureIntent = null;
}
}
from cordova-plugin-inappbrowser.
@gilbertogwa Dude, how do I add one more intention to your array of intentions ?
Array -> Intent[] intentArray;
from cordova-plugin-inappbrowser.
You can use Java syntax, for instance:
Intent[] intentArray;
intentArray = new Intent[]{takePictureIntent, anotherIntent};
Or
intentArray = new Intent[2];
intentArray[0] = takePictureIntent;
intentArray[1] = anotherIntent;
from cordova-plugin-inappbrowser.
You can use Java syntax, for instance:
Intent[] intentArray; intentArray = new Intent[]{takePictureIntent, anotherIntent};
Or
intentArray = new Intent[2]; intentArray[0] = takePictureIntent; intentArray[1] = anotherIntent;
Dude I think it was just a cache that was in my code, I deleted everything and rebooted the pc and it worked fine with that intentArray = new Intent[]{takePictureIntent, intentGallery};
from cordova-plugin-inappbrowser.
Found this issue, still having the issue with not having acces to the camera, I tried the solution of replacing the code in InAppBrowser.java that didn't work.
Do you have to remove the platform folder in a specific way? And add it in a special way?
Is there any update on this issue?
from cordova-plugin-inappbrowser.
Found this issue, still having the issue with not having acces to the camera, I tried the solution of replacing the code in InAppBrowser.java that didn't work.
Do you have to remove the platform folder in a specific way? And add it in a special way?
Is there any update on this issue?
I changed the InAppBrowser.java plugins folder and then removed the platform with the standard command and added it again, it worked for me on ionic 3 and 4
from cordova-plugin-inappbrowser.
Found this issue, still having the issue with not having acces to the camera, I tried the solution of replacing the code in InAppBrowser.java that didn't work.
Do you have to remove the platform folder in a specific way? And add it in a special way?
Is there any update on this issue?I changed the InAppBrowser.java plugins folder and then removed the platform with the standard command and added it again, it worked for me on ionic 3 and 4
I've changed the InAppBrowser.java file inside the node_modules/cordova-plugin-inappbrowser/src/android/ my input tag looks like this <input type="file" accept="image/*" capture="camera" capture="camera">
and it's not working while using ionic 4. It's still opening my device images/video folder and not the camera itself or giving me the option to choose between the gallery and camera
from cordova-plugin-inappbrowser.
Found this issue, still having the issue with not having acces to the camera, I tried the solution of replacing the code in InAppBrowser.java that didn't work.
Do you have to remove the platform folder in a specific way? And add it in a special way?
Is there any update on this issue?I changed the InAppBrowser.java plugins folder and then removed the platform with the standard command and added it again, it worked for me on ionic 3 and 4
I've changed the InAppBrowser.java file inside the node_modules/cordova-plugin-inappbrowser/src/android/ my input tag looks like this
<input type="file" accept="image/*" capture="camera" capture="camera">
and it's not working while using ionic 4. It's still opening my device images/video folder and not the camera itself or giving me the option to choose between the gallery and camera
Change the file in the plugins folder and not in node_modules
from cordova-plugin-inappbrowser.
Found this issue, still having the issue with not having acces to the camera, I tried the solution of replacing the code in InAppBrowser.java that didn't work.
Do you have to remove the platform folder in a specific way? And add it in a special way?
Is there any update on this issue?I changed the InAppBrowser.java plugins folder and then removed the platform with the standard command and added it again, it worked for me on ionic 3 and 4
I've changed the InAppBrowser.java file inside the node_modules/cordova-plugin-inappbrowser/src/android/ my input tag looks like this
<input type="file" accept="image/*" capture="camera" capture="camera">
and it's not working while using ionic 4. It's still opening my device images/video folder and not the camera itself or giving me the option to choose between the gallery and cameraChange the file in the plugins folder and not in node_modules
So I've reverted the changes in my node_modules, applied the changes to the file in the plugins/cordova-plugin-inappbrowser/src/android/InAppBrowser.java removed the platform, did a NPM install, added the platform again. Still not working.
from cordova-plugin-inappbrowser.
Dear,
@gilbertogwa , your solution works perfect until recently. I found camera cannot be opened on device which runs android 10, such as Huawei Mate 20 or Mate 20 Pro. The takePictureIntent is taken in and code is running without reporting errors, but there is no effect after clicking the camera option. I test normal browser html5 version is working fine.
Any idea for this, thanks!
from cordova-plugin-inappbrowser.
@davidrevo, I no longer participate in the project that uses this technology. So I can't help this issue. However, maybe, we should get together to try to solve this right in the plugin because it is already becoming a very frequent problem ... I can try to help in this issue tomorrow, but I need a functional POC, you could make available one that is already working on old version?
from cordova-plugin-inappbrowser.
Hi @gilbertogwa , thanks for answering the question. I guess this issue may be frequent on Android 10 devices. Do you mean I need to set up a demo project to review the issue? This issue is hard to investigate because after intent setup, it is null callback from device. So I guess whether it is Android 10 compatibility issue with webview?
from cordova-plugin-inappbrowser.
Hi @gilbertogwa , I just found the workaround solution to deal with Android Q, and will paste the code here for people who have the same trouble.
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.inappbrowser;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.provider.Browser;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.content.ContentValues;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaHttpAuthHandler;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginManager;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Locale;;
@SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private static final String NULL = "null";
protected static final String LOG_TAG = "InAppBrowser";
private static final String SELF = "_self";
private static final String SYSTEM = "_system";
private static final String EXIT_EVENT = "exit";
private static final String LOCATION = "location";
private static final String ZOOM = "zoom";
private static final String HIDDEN = "hidden";
private static final String LOAD_START_EVENT = "loadstart";
private static final String LOAD_STOP_EVENT = "loadstop";
private static final String LOAD_ERROR_EVENT = "loaderror";
private static final String CLEAR_ALL_CACHE = "clearcache";
private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
private static final String HARDWARE_BACK_BUTTON = "hardwareback";
private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction";
private static final String SHOULD_PAUSE = "shouldPauseOnSuspend";
private static final Boolean DEFAULT_HARDWARE_BACK = true;
private static final String USER_WIDE_VIEW_PORT = "useWideViewPort";
private static final String TOOLBAR_COLOR = "toolbarcolor";
private static final String CLOSE_BUTTON_CAPTION = "closebuttoncaption";
private static final String CLOSE_BUTTON_COLOR = "closebuttoncolor";
private static final String HIDE_NAVIGATION = "hidenavigationbuttons";
private static final String NAVIGATION_COLOR = "navigationbuttoncolor";
private static final String HIDE_URL = "hideurlbar";
private static final String FOOTER = "footer";
private static final String FOOTER_COLOR = "footercolor";
private static final List customizableOptions = Arrays.asList(CLOSE_BUTTON_CAPTION, TOOLBAR_COLOR, NAVIGATION_COLOR, CLOSE_BUTTON_COLOR, FOOTER_COLOR);
private InAppBrowserDialog dialog;
private WebView inAppWebView;
private EditText edittext;
private CallbackContext callbackContext;
private boolean showLocationBar = true;
private boolean showZoomControls = true;
private boolean openWindowHidden = false;
private boolean clearAllCache = false;
private boolean clearSessionCache = false;
private boolean hadwareBackButton = true;
private boolean mediaPlaybackRequiresUserGesture = false;
private boolean shouldPauseInAppBrowser = false;
private boolean useWideViewPort = true;
private ValueCallback<Uri> mUploadCallback;
private ValueCallback<Uri[]> mUploadCallbackLollipop;
private final static int FILECHOOSER_REQUESTCODE = 1;
private final static int FILECHOOSER_REQUESTCODE_LOLLIPOP = 2;
private String closeButtonCaption = "";
private String closeButtonColor = "";
private int toolbarColor = android.graphics.Color.LTGRAY;
private boolean hideNavigationButtons = false;
private String navigationButtonColor = "";
private boolean hideUrlBar = false;
private boolean showFooter = false;
private String footerColor = "";
private String[] allowedSchemes;
private String mCM;
private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q;
private Uri mCameraUri;
/**
* Executes the request and returns PluginResult.
*
* @param action the action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext the callbackContext used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("open")) {
this.callbackContext = callbackContext;
final String url = args.getString(0);
String t = args.optString(1);
if (t == null || t.equals("") || t.equals(NULL)) {
t = SELF;
}
final String target = t;
final HashMap<String, String> features = parseFeature(args.optString(2));
LOG.d(LOG_TAG, "target = " + target);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String result = "";
// SELF
if (SELF.equals(target)) {
LOG.d(LOG_TAG, "in self");
/* This code exists for compatibility between 3.x and 4.x versions of Cordova.
* Previously the Config class had a static method, isUrlWhitelisted(). That
* responsibility has been moved to the plugins, with an aggregating method in
* PluginManager.
*/
Boolean shouldAllowNavigation = null;
if (url.startsWith("javascript:")) {
shouldAllowNavigation = true;
}
if (shouldAllowNavigation == null) {
try {
Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
shouldAllowNavigation = (Boolean)iuw.invoke(null, url);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
if (shouldAllowNavigation == null) {
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
PluginManager pm = (PluginManager)gpm.invoke(webView);
Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
shouldAllowNavigation = (Boolean)san.invoke(pm, url);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
// load in webview
if (Boolean.TRUE.equals(shouldAllowNavigation)) {
LOG.d(LOG_TAG, "loading in webview");
webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.SCHEME_TEL))
{
try {
LOG.d(LOG_TAG, "loading in dialer");
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
// load in InAppBrowser
else {
LOG.d(LOG_TAG, "loading in InAppBrowser");
result = showWebPage(url, features);
}
}
// SYSTEM
else if (SYSTEM.equals(target)) {
LOG.d(LOG_TAG, "in system");
result = openExternal(url);
}
// BLANK - or anything else
else {
LOG.d(LOG_TAG, "in blank");
result = showWebPage(url, features);
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
});
}
else if (action.equals("close")) {
closeDialog();
}
else if (action.equals("injectScriptCode")) {
String jsWrapper = null;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId());
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectScriptFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleCode")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("show")) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.show();
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
else if (action.equals("hide")) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.hide();
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
else {
return false;
}
return true;
}
/**
* Called when the view navigates.
*/
@Override
public void onReset() {
closeDialog();
}
/**
* Called when the system is about to start resuming a previous activity.
*/
@Override
public void onPause(boolean multitasking) {
if (shouldPauseInAppBrowser) {
inAppWebView.onPause();
}
}
/**
* Called when the activity will start interacting with the user.
*/
@Override
public void onResume(boolean multitasking) {
if (shouldPauseInAppBrowser) {
inAppWebView.onResume();
}
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
closeDialog();
}
/**
* Inject an object (script or style) into the InAppBrowser WebView.
*
* This is a helper method for the inject{Script|Style}{Code|File} API calls, which
* provides a consistent method for injecting JavaScript code into the document.
*
* If a wrapper string is supplied, then the source string will be JSON-encoded (adding
* quotes) and wrapped using string formatting. (The wrapper string should have a single
* '%s' marker)
*
* @param source The source object (filename or script/style text) to inject into
* the document.
* @param jsWrapper A JavaScript string to wrap the source string in, so that the object
* is properly injected, or null if the source string is JavaScript text
* which should be executed directly.
*/
private void injectDeferredObject(String source, String jsWrapper) {
if (inAppWebView!=null) {
String scriptToInject;
if (jsWrapper != null) {
org.json.JSONArray jsonEsc = new org.json.JSONArray();
jsonEsc.put(source);
String jsonRepr = jsonEsc.toString();
String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1);
scriptToInject = String.format(jsWrapper, jsonSourceString);
} else {
scriptToInject = source;
}
final String finalScriptToInject = scriptToInject;
this.cordova.getActivity().runOnUiThread(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
// This action will have the side-effect of blurring the currently focused element
inAppWebView.loadUrl("javascript:" + finalScriptToInject);
} else {
inAppWebView.evaluateJavascript(finalScriptToInject, null);
}
}
});
} else {
LOG.d(LOG_TAG, "Can't inject code into the system browser");
}
}
/**
* Put the list of features into a hash map
*
* @param optString
* @return
*/
private HashMap<String, String> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, String> map = new HashMap<String, String>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
String value = option.nextToken();
if (!customizableOptions.contains(key)){
value = value.equals("yes") || value.equals("no") ? value : "yes";
}
map.put(key, value);
}
}
return map;
}
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @return "" if ok, or error message.
*/
public String openExternal(String url) {
try {
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW);
// Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
// Adding the MIME type to http: URLs causes them to not be handled by the downloader.
Uri uri = Uri.parse(url);
if ("file".equals(uri.getScheme())) {
intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri));
} else {
intent.setData(uri);
}
intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName());
this.cordova.getActivity().startActivity(intent);
return "";
// not catching FileUriExposedException explicitly because buildtools<24 doesn't know about it
} catch (java.lang.RuntimeException e) {
LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString());
return e.toString();
}
}
/**
* Closes the dialog
*/
public void closeDialog() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final WebView childView = inAppWebView;
// The JS protects against multiple calls, so this should happen only when
// closeDialog() is called by other native code.
if (childView == null) {
return;
}
childView.setWebViewClient(new WebViewClient() {
// NB: wait for about:blank before dismissing
public void onPageFinished(WebView view, String url) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
});
// NB: From SDK 19: "If you call methods on WebView from any thread
// other than your app's UI thread, it can cause unexpected results."
// http://developer.android.com/guide/webapps/migrating.html#Threads
childView.loadUrl("about:blank");
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
public void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
/**
* Can the web browser go back?
* @return boolean
*/
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
/**
* Has the user set the hardware back button to go back
* @return boolean
*/
public boolean hardwareBack() {
return hadwareBackButton;
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.inAppWebView.canGoForward()) {
this.inAppWebView.goForward();
}
}
/**
* Navigate to the new page
*
* @param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.inAppWebView.loadUrl("http://" + url);
} else {
this.inAppWebView.loadUrl(url);
}
this.inAppWebView.requestFocus();
}
/**
* Should we show the location bar?
*
* @return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
private InAppBrowser getInAppBrowser(){
return this;
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @param features jsonObject
*/
public String showWebPage(final String url, HashMap<String, String> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
openWindowHidden = false;
mediaPlaybackRequiresUserGesture = false;
if (features != null) {
String show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.equals("yes") ? true : false;
}
if(showLocationBar) {
String hideNavigation = features.get(HIDE_NAVIGATION);
String hideUrl = features.get(HIDE_URL);
if(hideNavigation != null) hideNavigationButtons = hideNavigation.equals("yes") ? true : false;
if(hideUrl != null) hideUrlBar = hideUrl.equals("yes") ? true : false;
}
String zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.equals("yes") ? true : false;
}
String hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.equals("yes") ? true : false;
}
String hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.equals("yes") ? true : false;
} else {
hadwareBackButton = DEFAULT_HARDWARE_BACK;
}
String mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION);
if (mediaPlayback != null) {
mediaPlaybackRequiresUserGesture = mediaPlayback.equals("yes") ? true : false;
}
String cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.equals("yes") ? true : false;
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.equals("yes") ? true : false;
}
}
String shouldPause = features.get(SHOULD_PAUSE);
if (shouldPause != null) {
shouldPauseInAppBrowser = shouldPause.equals("yes") ? true : false;
}
String wideViewPort = features.get(USER_WIDE_VIEW_PORT);
if (wideViewPort != null ) {
useWideViewPort = wideViewPort.equals("yes") ? true : false;
}
String closeButtonCaptionSet = features.get(CLOSE_BUTTON_CAPTION);
if (closeButtonCaptionSet != null) {
closeButtonCaption = closeButtonCaptionSet;
}
String closeButtonColorSet = features.get(CLOSE_BUTTON_COLOR);
if (closeButtonColorSet != null) {
closeButtonColor = closeButtonColorSet;
}
String toolbarColorSet = features.get(TOOLBAR_COLOR);
if (toolbarColorSet != null) {
toolbarColor = android.graphics.Color.parseColor(toolbarColorSet);
}
String navigationButtonColorSet = features.get(NAVIGATION_COLOR);
if (navigationButtonColorSet != null) {
navigationButtonColor = navigationButtonColorSet;
}
String showFooterSet = features.get(FOOTER);
if (showFooterSet != null) {
showFooter = showFooterSet.equals("yes") ? true : false;
}
String footerColorSet = features.get(FOOTER_COLOR);
if (footerColorSet != null) {
footerColor = footerColorSet;
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
private View createCloseButton(int id){
View _close;
Resources activityRes = cordova.getActivity().getResources();
if (closeButtonCaption != "") {
// Use TextView for text
TextView close = new TextView(cordova.getActivity());
close.setText(closeButtonCaption);
close.setTextSize(20);
if (closeButtonColor != "") close.setTextColor(android.graphics.Color.parseColor(closeButtonColor));
close.setGravity(android.view.Gravity.CENTER_VERTICAL);
close.setPadding(this.dpToPixels(10), 0, this.dpToPixels(10), 0);
_close = close;
}
else {
ImageButton close = new ImageButton(cordova.getActivity());
int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
Drawable closeIcon = activityRes.getDrawable(closeResId);
if (closeButtonColor != "") close.setColorFilter(android.graphics.Color.parseColor(closeButtonColor));
close.setImageDrawable(closeIcon);
close.setScaleType(ImageView.ScaleType.FIT_CENTER);
if (Build.VERSION.SDK_INT >= 16)
close.getAdjustViewBounds();
_close = close;
}
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
_close.setLayoutParams(closeLayoutParams);
if (Build.VERSION.SDK_INT >= 16)
_close.setBackground(null);
else
_close.setBackgroundDrawable(null);
_close.setContentDescription("Close Button");
_close.setId(Integer.valueOf(id));
_close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
return _close;
}
@SuppressLint("NewApi")
public void run() {
// CB-6702 InAppBrowser hangs when opening more than one instance
if (dialog != null) {
dialog.dismiss();
};
// Let's create the main dialog
dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setInAppBroswer(getInAppBrowser());
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
//Please, no more black!
toolbar.setBackgroundColor(toolbarColor);
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(Integer.valueOf(1));
// Back button
ImageButton back = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(Integer.valueOf(2));
Resources activityRes = cordova.getActivity().getResources();
int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
Drawable backIcon = activityRes.getDrawable(backResId);
if (navigationButtonColor != "") back.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
if (Build.VERSION.SDK_INT >= 16)
back.setBackground(null);
else
back.setBackgroundDrawable(null);
back.setImageDrawable(backIcon);
back.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
back.getAdjustViewBounds();
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
ImageButton forward = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(Integer.valueOf(3));
int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
Drawable fwdIcon = activityRes.getDrawable(fwdResId);
if (navigationButtonColor != "") forward.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
if (Build.VERSION.SDK_INT >= 16)
forward.setBackground(null);
else
forward.setBackgroundDrawable(null);
forward.setImageDrawable(fwdIcon);
forward.setScaleType(ImageView.ScaleType.FIT_CENTER);
forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
forward.getAdjustViewBounds();
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(Integer.valueOf(4));
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Header Close/Done button
View close = createCloseButton(5);
toolbar.addView(close);
// Footer
RelativeLayout footer = new RelativeLayout(cordova.getActivity());
int _footerColor;
if(footerColor != ""){
_footerColor = Color.parseColor(footerColor);
}else{
_footerColor = android.graphics.Color.LTGRAY;
}
footer.setBackgroundColor(_footerColor);
RelativeLayout.LayoutParams footerLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44));
footerLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
footer.setLayoutParams(footerLayout);
if (closeButtonCaption != "") footer.setPadding(this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8));
footer.setHorizontalGravity(Gravity.LEFT);
footer.setVerticalGravity(Gravity.BOTTOM);
View footerClose = createCloseButton(7);
footer.addView(footerClose);
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));
// File Chooser Implemented ChromeClient
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView) {
// For Android 5.0+
public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if(Build.VERSION.SDK_INT >=23 && (cordova.getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || cordova.getActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
cordova.getActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
LOG.d(LOG_TAG, "File Chooser 5.0+");
// If callback exists, finish it.
if(mUploadCallbackLollipop != null) {
mUploadCallbackLollipop.onReceiveValue(null);
}
mUploadCallbackLollipop = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if(takePictureIntent.resolveActivity(cordova.getActivity().getPackageManager()) != null) {
File photoFile = null;
Uri photoUri = null;
if (isAndroidQ) {
// Android Q compatibility
photoUri = createImageUri();
mCameraUri = photoUri;
if (photoUri != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
} else {
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (IOException ex) {
Log.e(LOG_TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
}
// Create File Chooser Intent
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if(takePictureIntent != null){
intentArray = new Intent[]{takePictureIntent};
}else{
intentArray = new Intent[0];
}
Locale localeInfo = cordova.getActivity().getApplicationContext().getResources()
.getConfiguration().getLocales().get(0);
String lang = localeInfo.toLanguageTag();
String title;
if (lang.startsWith("en"))
{
title = "Choose the source";
} else if (lang.startsWith("es"))
{
title = "Seleccione el origen";
} else
{
title = "Escolha a origem";
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, title);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
// Run cordova startActivityForResult
cordova.startActivityForResult(InAppBrowser.this, chooserIntent, 120);
return true;
}
private Uri createImageUri() {
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {
return cordova.getActivity().getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
} else {
return cordova.getActivity().getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
}
}
// For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
LOG.d(LOG_TAG, "File Chooser 4.1+");
// Call file chooser for Android 3.0+
openFileChooser(uploadMsg, acceptType);
}
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType)
{
LOG.d(LOG_TAG, "File Chooser 3.0+");
mUploadCallback = uploadMsg;
Intent content = new Intent(Intent.ACTION_GET_CONTENT);
content.addCategory(Intent.CATEGORY_OPENABLE);
// run startActivityForResult
cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE);
}
});
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(showZoomControls);
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
}
String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
String appendUserAgent = preferences.getString("AppendUserAgent", null);
if (overrideUserAgent != null) {
settings.setUserAgentString(overrideUserAgent);
}
if (appendUserAgent != null) {
settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent);
}
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if (enableDatabase) {
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
if (clearAllCache) {
CookieManager.getInstance().removeAllCookie();
} else if (clearSessionCache) {
CookieManager.getInstance().removeSessionCookie();
}
// Enable Thirdparty Cookies on >=Android 5.0 device
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(inAppWebView,true);
}
inAppWebView.loadUrl(url);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(useWideViewPort);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar if they haven't been disabled
if (!hideNavigationButtons) toolbar.addView(actionButtonContainer);
if (!hideUrlBar) toolbar.addView(edittext);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
RelativeLayout webViewLayout = new RelativeLayout(cordova.getActivity());
webViewLayout.addView(inAppWebView);
main.addView(webViewLayout);
// Don't add the footer unless it's been enabled
if (showFooter) {
webViewLayout.addView(footer);
}
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
// the goal of openhidden is to load the url and not display it
// Show() needs to be called to cause the URL to be loaded
if(openWindowHidden) {
dialog.hide();
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
private File createImageFile() throws IOException{
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
/**
* Create a new plugin success result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
*/
private void sendUpdate(JSONObject obj, boolean keepCallback) {
sendUpdate(obj, keepCallback, PluginResult.Status.OK);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
* @param status the status code to return to the JavaScript environment
*/
private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
if (callbackContext != null) {
PluginResult result = new PluginResult(status, obj);
result.setKeepCallback(keepCallback);
callbackContext.sendPluginResult(result);
if (!keepCallback) {
callbackContext = null;
}
}
}
/**
* Receive File Data from File Chooser
*
* @param requestCode the requested code from chromeclient
* @param resultCode the result code returned from android system
* @param intent the data from android file chooser
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// For Android >= 5.0
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
LOG.d(LOG_TAG, "onActivityResult (For Android >= 5.0)");
Uri[] results = null;
//Check if response is positive
if(resultCode== Activity.RESULT_OK){
if(requestCode == FILECHOOSER_REQUESTCODE){
if(null == mUploadCallbackLollipop){
return;
}
if(intent == null || intent.getData() == null){
//Capture Photo if no image available
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = intent.getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUploadCallbackLollipop .onReceiveValue(results);
mUploadCallbackLollipop = null;
}
// For Android < 5.0
else {
LOG.d(LOG_TAG, "onActivityResult (For Android < 5.0)");
// If RequestCode or Callback is Invalid
if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) {
super.onActivityResult(requestCode, resultCode, intent);
return;
}
if (null == mUploadCallback) return;
Uri result = intent == null || resultCode != cordova.getActivity().RESULT_OK ? null : intent.getData();
mUploadCallback.onReceiveValue(result);
mUploadCallback = null;
}
}
/**
* The webview client receives notifications about appView
*/
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
/**
* Constructor.
*
* @param webView
* @param mEditText
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
this.webView = webView;
this.edittext = mEditText;
}
/**
* Override the URL that should be loaded
*
* This handles a small subset of all the URIs that would be encountered.
*
* @param webView
* @param url
*/
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
} else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
} else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:" + address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
// Test for whitelisted custom scheme names like mycoolapp:// or twitteroauthresponse:// (Twitter Oauth Response)
else if (!url.startsWith("http:") && !url.startsWith("https:") && url.matches("^[a-z]*://.*?$")) {
if (allowedSchemes == null) {
String allowed = preferences.getString("AllowedSchemes", "");
allowedSchemes = allowed.split(",");
}
if (allowedSchemes != null) {
for (String scheme : allowedSchemes) {
if (url.startsWith(scheme)) {
try {
JSONObject obj = new JSONObject();
obj.put("type", "customscheme");
obj.put("url", url);
sendUpdate(obj, true);
return true;
} catch (JSONException ex) {
LOG.e(LOG_TAG, "Custom Scheme URI passed in has caused a JSON error.");
}
}
}
}
}
return false;
}
/*
* onPageStarted fires the LOAD_START_EVENT
*
* @param view
* @param url
* @param favicon
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc = "";
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
}
else
{
// Assume that everything is HTTP at this point, because if we don't specify,
// it really should be. Complain loudly about this!!!
LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI");
newloc = "http://" + url;
}
// Update the UI if we haven't already
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_START_EVENT);
obj.put("url", newloc);
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
}
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush();
} else {
CookieSyncManager.getInstance().sync();
}
// https://issues.apache.org/jira/browse/CB-11248
view.clearFocus();
view.requestFocus();
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
obj.put("url", url);
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", failingUrl);
obj.put("code", errorCode);
obj.put("message", description);
sendUpdate(obj, true, PluginResult.Status.ERROR);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
/**
* On received http auth request.
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
// Check if there is some plugin which can resolve this auth challenge
PluginManager pluginManager = null;
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
pluginManager = (PluginManager)gpm.invoke(webView);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
if (pluginManager == null) {
try {
Field pmf = webView.getClass().getField("pluginManager");
pluginManager = (PluginManager)pmf.get(webView);
} catch (NoSuchFieldException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) {
return;
}
// By default handle 401 like we'd normally do!
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
}
from cordova-plugin-inappbrowser.
Hi @davidrevo I tried your solution, but I ran in to an error:
InAppBrowser.java:151: error: cannot find symbol
private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q;
^
symbol: variable Q
location: class VERSION_CODES
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error
FAILURE: Build failed with an exception.
I changed the InAppBrowser.java file, removed the platfrom did a NPM install added android platform and started a build.
from cordova-plugin-inappbrowser.
Hi @PlanB007 ,
Try change to those settings,
defaultTargetSdkVersion=29
defaultCompileSdkVersion=29
from cordova-plugin-inappbrowser.
@davidrevo That didn't work, keeps getting the same error
from cordova-plugin-inappbrowser.
@davidrevo That didn't work, keeps getting the same error
Hi @PlanB007,
Add after import android.widget.TextView the import android.content.ContentValues;
After change line private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q; to private boolean isAndroidQ = Build.VERSION.SDK_INT >= 29 and test;
This work for me! The only issue left is I can choose between the files folder & camcorder (video only). I want to acces the camera. The HTML is used is <input accept="image/png, image/jpeg" type="file" capture="">
any idea? In chrome it opens the camera, and not the camcorder.
from cordova-plugin-inappbrowser.
I am not using cordova but I was experiencing the same problem with my in app web view, i.e. not bring up the camera when running on an Android 10 device and only showing the file chooser instead, so I added the new section of code for Android Q to the takePictureIntent method and lo and behold the camera is now offered as an option (thanks!), however nothing happened inside onActivityResult so I added the following
else if (mCameraUri != null)
{
results = new Uri[]{mCameraUri};
}
and everything works
from cordova-plugin-inappbrowser.
@davidrevo That didn't work, keeps getting the same error
Hi @PlanB007,
Add after import android.widget.TextView the import android.content.ContentValues;
After change line private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q; to private boolean isAndroidQ = Build.VERSION.SDK_INT >= 29 and test;This work for me! The only issue left is I can choose between the files folder & camcorder (video only). I want to acces the camera. The HTML is used is
<input accept="image/png, image/jpeg" type="file" capture="">
any idea? In chrome it opens the camera, and not the camcorder.Do you mean you want to access camera not video recorder? Need to change this
Intent takePictureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
=>
Intent takePictureIntent = new Intent(MediaStore. ACTION_IMAGE_CAPTURE);
This did the trick for me! A platform remove, npm install, platform add was required. You, sir, are a legend. You made my day!
from cordova-plugin-inappbrowser.
@KenCorbettJr Will make a pull request tonight of my edited/working version with credits to @davidrevo
from cordova-plugin-inappbrowser.
@KenCorbettJr made the PR with my version, this all was pretty new for me. Hoping that the people who are working on this plugin are nice to me 😃
from cordova-plugin-inappbrowser.
When testing the last version, camera indeed opens but file field is not populated with the captured image. Strange enough the same issue occurs when an image is selected from the gallery. With the formal 3.0.0 version gallery selection works.
Any thoughts what could be the issue? @davidrevo
from cordova-plugin-inappbrowser.
Hi, I wonder if this is related, I have opened Amzon.com using inAppBrowser but when I click on the camera or microphone Icon, I get the following error, it it possible to get this working?
The webpage at intent://amazon.com/........ could not be loaded because : net::ERR_UNKNOWN_URL_SCHEME
from cordova-plugin-inappbrowser.
Hi, I wonder if this is related, I have opened Amzon.com using inAppBrowser but when I click on the camera or microphone Icon, I get the following error, it it possible to get this working?
The webpage at intent://amazon.com/........ could not be loaded because : net::ERR_UNKNOWN_URL_SCHEME
This doesn't seem relevant to the main issue, looks like an error on the Amzon.com side 🤔
from cordova-plugin-inappbrowser.
Hi, I wonder if this is related, I have opened Amzon.com using inAppBrowser but when I click on the camera or microphone Icon, I get the following error, it it possible to get this working?
The webpage at intent://amazon.com/........ could not be loaded because : net::ERR_UNKNOWN_URL_SCHEMEThis doesn't seem relevant to the main issue, looks like an error on the Amzon.com side 🤔
no Amazon website is fine. Chrome can open the camera.
from cordova-plugin-inappbrowser.
@davidrevo @PlanB007 Hi, thank you for your input. The cordova inappbrowser invokes the camera now. Unfortunately, once the video or picture is taken it is not being captured in the form. I tried http://regular-rod.surge.sh as a url. I'd appreciate your input in this. Thank you.
from cordova-plugin-inappbrowser.
i'm getting the same issue as @shlomoco and @albosta :( Any update ?
from cordova-plugin-inappbrowser.
@albosta @shlomoco After some debugging i managed to get it working, maybe it can be of some help to you.
I changed the part in onActivityResult, it only checked mCM but that is empty when it's android Q. so this should check if there has been a picture taken with an android Q device if not it will go through the regular flow
if(mCameraUri!= null){ results = new Uri[]{mCameraUri}; }else if(mCM != null){ results = new Uri[]{Uri.parse(mCM)}; }
from cordova-plugin-inappbrowser.
Actually I was still having the same issue with image not loading on Android 10 and in some devices not even opening the camera, the problem was that the code for the temporary file creation in here:
private File createImageFile() throws IOException{
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
I changed the Environment.getExternalStoragePublicDirectory as it is deprecated on API 29 onwards, using this:
private File createImageFile() throws IOException{
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// let's use the new api for accessing external storage on 29 onwards
File storageDir = this.cordova.getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File file = new File(storageDir, imageFileName + ".jpg");
return file;
} else {
// was working well on older droids so let's leave it as is.
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = File.createTempFile(imageFileName,".jpg",storageDir);
return file;
}
}
Thought I just left this here in case someone else is having the same struggle.
from cordova-plugin-inappbrowser.
Are there any news on this issue? It's still a big problem for me using the newest version of InAppBrowser. Normal chrome does it right but IAB opens filemanager instead of camera, even though the input says it should use camera.
from cordova-plugin-inappbrowser.
https://imagens.canaltech.com.br/295234.547324-Dancarinos-de-Funeral.gif
from cordova-plugin-inappbrowser.
@ReneDyhr The above changes can also be applied to 5.0.1-dev. What I changed in src/android/InAppBrowser.java was:
Add:
import android.app.Activity;
import android.Manifest;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
Add:
private String mCM;
Change onShowFileChooser to:
// For Android 5.0+
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if(Build.VERSION.SDK_INT >=23 && (cordova.getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || cordova.getActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
cordova.getActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
LOG.d(LOG_TAG, "File Chooser 5.0+");
// If callback exists, finish it.
if(mUploadCallback != null) {
mUploadCallback.onReceiveValue(null);
}
mUploadCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(cordova.getActivity().getPackageManager()) != null) {
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(LOG_TAG, "Image file creation failed", ex);
}
if(photoFile != null){
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
}else{
takePictureIntent = null;
}
}
// Create File Chooser Intent
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if(takePictureIntent != null){
intentArray = new Intent[]{takePictureIntent};
}else{
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
// Run cordova startActivityForResult
cordova.startActivityForResult(InAppBrowser.this, chooserIntent, FILECHOOSER_REQUESTCODE);
return true;
}
Note that I did not include Android < 5.0 for onShowFileChooser
Add:
private File createImageFile() throws IOException{
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// let's use the new api for accessing external storage on 29 onwards
File storageDir = this.cordova.getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File file = new File(storageDir, imageFileName + ".jpg");
return file;
} else {
// was working well on older droids so let's leave it as is.
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = File.createTempFile(imageFileName,".jpg",storageDir);
return file;
}
}
Credits to the people above
from cordova-plugin-inappbrowser.
I solve change InAppBrowser plugin. I merged solution on https://stackoverflow.com/questions/51168600/webview-open-camera-from-input-field-without-filechooser.
Follow the changes:
See the changes made in InAppBrowser class from plugin version 3.0.0
1 - include imports:
import android.app.Activity; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date;
2 - declare variavel;
private String mCM;
3 - Replace onShowFileChooser code
// For Android 5.0+ public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { LOG.d(LOG_TAG, "File Chooser 5.0+"); // If callback exists, finish it. if(mUploadCallbackLollipop != null) { mUploadCallbackLollipop.onReceiveValue(null); } mUploadCallbackLollipop = filePathCallback; Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(takePictureIntent.resolveActivity(cordova.getActivity().getPackageManager()) != null) { File photoFile = null; try{ photoFile = createImageFile(); takePictureIntent.putExtra("PhotoPath", mCM); }catch(IOException ex){ Log.e(LOG_TAG, "Image file creation failed", ex); } if(photoFile != null){ mCM = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); }else{ takePictureIntent = null; } } // Create File Chooser Intent Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType("*/*"); Intent[] intentArray; if(takePictureIntent != null){ intentArray = new Intent[]{takePictureIntent}; }else{ intentArray = new Intent[0]; } Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, "Selecione a imagem"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); // Run cordova startActivityForResult cordova.startActivityForResult(InAppBrowser.this, chooserIntent, FILECHOOSER_REQUESTCODE); return true; }
4 - create method
private File createImageFile() throws IOException{ @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "img_"+timeStamp+"_"; File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); return File.createTempFile(imageFileName,".jpg",storageDir); }
5 - Replace onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent intent) { // For Android >= 5.0 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LOG.d(LOG_TAG, "onActivityResult (For Android >= 5.0)"); Uri[] results = null; //Check if response is positive if(resultCode== Activity.RESULT_OK){ if(requestCode == FILECHOOSER_REQUESTCODE){ if(null == mUploadCallbackLollipop){ return; } if(intent == null || intent.getData() == null){ //Capture Photo if no image available if(mCM != null){ results = new Uri[]{Uri.parse(mCM)}; } }else{ String dataString = intent.getDataString(); if(dataString != null){ results = new Uri[]{Uri.parse(dataString)}; } } } } mUploadCallbackLollipop .onReceiveValue(results); mUploadCallbackLollipop = null; } // For Android < 5.0 else { LOG.d(LOG_TAG, "onActivityResult (For Android < 5.0)"); // If RequestCode or Callback is Invalid if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) { super.onActivityResult(requestCode, resultCode, intent); return; } if (null == mUploadCallback) return; Uri result = intent == null || resultCode != cordova.getActivity().RESULT_OK ? null : intent.getData(); mUploadCallback.onReceiveValue(result); mUploadCallback = null; } }
you are the best :D
from cordova-plugin-inappbrowser.
Which classes should I put all of this code in?
from cordova-plugin-inappbrowser.
Still no progress on this? I am willing to use development branch, really need this feature :/
from cordova-plugin-inappbrowser.
I solve change InAppBrowser plugin. I merged solution on https://stackoverflow.com/questions/51168600/webview-open-camera-from-input-field-without-filechooser.
Follow the changes:
See the changes made in InAppBrowser class from plugin version 3.0.0
1 - include imports:import android.app.Activity; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date;
2 - declare variavel;
private String mCM;
3 - Replace onShowFileChooser code
// For Android 5.0+ public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { LOG.d(LOG_TAG, "File Chooser 5.0+"); // If callback exists, finish it. if(mUploadCallbackLollipop != null) { mUploadCallbackLollipop.onReceiveValue(null); } mUploadCallbackLollipop = filePathCallback; Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(takePictureIntent.resolveActivity(cordova.getActivity().getPackageManager()) != null) { File photoFile = null; try{ photoFile = createImageFile(); takePictureIntent.putExtra("PhotoPath", mCM); }catch(IOException ex){ Log.e(LOG_TAG, "Image file creation failed", ex); } if(photoFile != null){ mCM = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); }else{ takePictureIntent = null; } } // Create File Chooser Intent Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType("*/*"); Intent[] intentArray; if(takePictureIntent != null){ intentArray = new Intent[]{takePictureIntent}; }else{ intentArray = new Intent[0]; } Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, "Selecione a imagem"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); // Run cordova startActivityForResult cordova.startActivityForResult(InAppBrowser.this, chooserIntent, FILECHOOSER_REQUESTCODE); return true; }
4 - create method
private File createImageFile() throws IOException{ @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "img_"+timeStamp+"_"; File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); return File.createTempFile(imageFileName,".jpg",storageDir); }
5 - Replace onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent intent) { // For Android >= 5.0 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LOG.d(LOG_TAG, "onActivityResult (For Android >= 5.0)"); Uri[] results = null; //Check if response is positive if(resultCode== Activity.RESULT_OK){ if(requestCode == FILECHOOSER_REQUESTCODE){ if(null == mUploadCallbackLollipop){ return; } if(intent == null || intent.getData() == null){ //Capture Photo if no image available if(mCM != null){ results = new Uri[]{Uri.parse(mCM)}; } }else{ String dataString = intent.getDataString(); if(dataString != null){ results = new Uri[]{Uri.parse(dataString)}; } } } } mUploadCallbackLollipop .onReceiveValue(results); mUploadCallbackLollipop = null; } // For Android < 5.0 else { LOG.d(LOG_TAG, "onActivityResult (For Android < 5.0)"); // If RequestCode or Callback is Invalid if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) { super.onActivityResult(requestCode, resultCode, intent); return; } if (null == mUploadCallback) return; Uri result = intent == null || resultCode != cordova.getActivity().RESULT_OK ? null : intent.getData(); mUploadCallback.onReceiveValue(result); mUploadCallback = null; } }
you are the best :D
Hey team, just gave the InAppBrowser plugin a spin for PWA, Android, and iOS builds. Looks like the changes impacted IOS InAppBrowser functionalities, and for Android, it doesn't seem like we've cracked it yet. Any ideas? 🕵️♂️
from cordova-plugin-inappbrowser.
Related Issues (20)
- Calling window.print() does not work
- Keychain not work with inappbrowser HOT 1
- Disable close button (Done) for iOS
- InAppBrowser does not open Youtube Links Properly HOT 12
- The preference name "MediaPlaybackRequiresUserAction" has been deprecated. It is recommended to replace this preference with "MediaTypesRequiringUserActionForPlayback."
- When can we expect latest 6.0.0 version release on npm? HOT 1
- The www/inappbrowser.css file should be removed because it was only for the Windows platform HOT 1
- Cannot build iOS Ionic Capacitor project HOT 5
- 6.0.0 Update throws error while archiving iOS project: "'Cordova/CDVWebViewProcessPoolFactory.h' file not found" HOT 1
- "browser.on('loaderror')" does not work properly on iOS.
- executeScript not working in colab HOT 4
- How to build this plugin for node_modules? HOT 2
- Add option to respect/ignore safe area on iOS
- ref.executeScript can't write clipboard HOT 5
- window.open doesnt work inside the opened webview HOT 2
- Warning when submitting to play store - JavaScript Interface Injection HOT 3
- @awesome-cordova-plugins/in-app-browser, this plugin is not sending the device id to azure while login + iOS HOT 3
- Angular 15 webpage not loading correctly in inappbrowser (Android < 11) HOT 1
- Hide Location & toolbar on scroll
- No visible @interface for 'UIApplication' when building an app for iOS HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from cordova-plugin-inappbrowser.