Commit 860a42e2 authored by pichillilorenzo's avatar pichillilorenzo

v0.4.0

parent c7356f33
This diff is collapsed.
## 0.4.0
- removed `target` parameter to `InAppBrowser.open()` method. To open the url on the system browser, use the `openWithSystemBrowser: true` option
- fixes for the `_ChannelManager` private class
- fixed `EXC_BAD_INSTRUCTION` onLoadStart in Swift
- added `openWithSystemBrowser` and `isLocalFile` options
- added `InAppBrowser.openWithSystemBrowser` method
- added `InAppBrowser.openOnLocalhost` method
- added `InAppBrowser.loadFile` method
## 0.3.2
- fixed WebView.storyboard path for iOS
......
......@@ -136,8 +136,8 @@ class _MyAppState extends State<MyApp> {
title: const Text('Flutter InAppBrowser Plugin example app'),
),
body: new Center(
child: new RaisedButton(onPressed: () {
inAppBrowser.open(url: "https://flutter.io/", options: {
child: new RaisedButton(onPressed: () async {
await inAppBrowser.open(url: "https://flutter.io/", options: {
"useShouldOverrideUrlLoading": true,
"useOnLoadResource": true
});
......@@ -155,8 +155,10 @@ class _MyAppState extends State<MyApp> {
Opens a URL in a new InAppBrowser instance or the system browser.
**NOTE**: If you open the given `url` with the system browser (`openWithSystemBrowser: true`), you wont be able to use the `InAppBrowser` methods!
```dart
inAppBrowser.open({String url = "about:blank", Map<String, String> headers = const {}, String target = "_self", Map<String, dynamic> options = const {}});
inAppBrowser.open({String url = "about:blank", Map<String, String> headers = const {}, Map<String, dynamic> options = const {}});
```
Opens an `url` in a new `InAppBrowser` instance or the system browser.
......@@ -165,17 +167,13 @@ Opens an `url` in a new `InAppBrowser` instance or the system browser.
- `headers`: The additional headers to be used in the HTTP request for this URL, specified as a map from name to value.
- `target`: The target in which to load the `url`, an optional parameter that defaults to `_self`.
- `_self`: Opens in the `InAppBrowser`.
- `_blank`: Opens in the `InAppBrowser`.
- `_system`: Opens in the system's web browser.
- `options`: Options for the `InAppBrowser`.
All platforms support:
- __useShouldOverrideUrlLoading__: Set to `true` to be able to listen at the `shouldOverrideUrlLoading` event. The default value is `false`.
- __useOnLoadResource__: Set to `true` to be able to listen at the `onLoadResource()` event. The default value is `false`.
- __openWithSystemBrowser__: Set to `true` to open the given `url` with the system browser. The default value is `false`.
- __isLocalFile__: Set to `true` if the `url` is pointing to a local file (the file must be addded in the `assets` section of your `pubspec.yaml`. See `loadFile()` explanation). The default value is `false`.
- __clearCache__: Set to `true` to have all the browser's cache cleared before the new window is opened. The default value is `false`.
- __userAgent___: Set the custom WebView's user-agent.
- __javaScriptEnabled__: Set to `true` to enable JavaScript. The default value is `true`.
......@@ -233,6 +231,33 @@ inAppBrowser.open('https://flutter.io/', options: {
});
```
#### static Future\<void\> InAppBrowser.openWithSystemBrowser
This is a static method that opens an `url` in the system browser.
This has the same behaviour of an `InAppBrowser` instance calling the `open()` method with option `openWithSystemBrowser: true`.
```dart
InAppBrowser.openWithSystemBrowser(String url);
```
#### Future\<void\> InAppBrowser.openOnLocalhost
Serve the `assetFilePath` from Flutter assets on http://localhost:`port`/. It is similar to `InAppBrowser.open()` with option `isLocalFile: true`, but it starts a server.
**NOTE for iOS**: For the iOS Platform, you need to add the `NSAllowsLocalNetworking` key with `true` in the `Info.plist` file (See [ATS Configuration Basics](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW35):
```xml
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
```
The `NSAllowsLocalNetworking` key is available since **iOS 10**.
```dart
inAppBrowser.openOnLocalhost(String assetFilePath, {int port = 8080, Map<String, String> headers = const {}, Map<String, dynamic> options = const {}});
```
#### Events
Event fires when the `InAppBrowser` starts to load an `url`.
......@@ -305,6 +330,42 @@ Loads the given `url` with optional `headers` specified as a map from name to va
inAppBrowser.loadUrl(String url, {Map<String, String> headers = const {}});
```
#### Future\<void\> InAppBrowser.loadFile
Loads the given `assetFilePath` with optional `headers` specified as a map from name to value.
To be able to load your local files (assets, js, css, etc.), you need to add them in the `assets` section of the `pubspec.yaml` file, otherwise they cannot be found!
Example of a `pubspec.yaml` file:
```yaml
...
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
assets:
- assets/index.html
- assets/css/
- assets/images/
...
```
Example of a `main.dart` file:
```dart
...
inAppBrowser.loadFile("assets/index.html");
...
```
```dart
inAppBrowser.loadFile(String assetFilePath, {Map<String, String> headers = const {}});
```
#### Future\<void\> InAppBrowser.show
Displays an `InAppBrowser` window that was opened hidden. Calling this has no effect if the `InAppBrowser` was already visible.
......@@ -379,7 +440,7 @@ inAppBrowser.isHidden();
#### Future\<String\> InAppBrowser.injectScriptCode
Injects JavaScript code into the `InAppBrowser` window and returns the result of the evaluation. (Only available when the target is set to `_blank` or to `_self`)
Injects JavaScript code into the `InAppBrowser` window and returns the result of the evaluation.
```dart
inAppBrowser.injectScriptCode(String source);
......@@ -387,7 +448,7 @@ inAppBrowser.injectScriptCode(String source);
#### Future\<void\> InAppBrowser.injectScriptFile
Injects a JavaScript file into the `InAppBrowser` window. (Only available when the target is set to `_blank` or to `_self`)
Injects a JavaScript file into the `InAppBrowser` window.
```dart
inAppBrowser.injectScriptFile(String urlFile);
......@@ -395,7 +456,7 @@ inAppBrowser.injectScriptFile(String urlFile);
#### Future\<void\> InAppBrowser.injectStyleCode
Injects CSS into the `InAppBrowser` window. (Only available when the target is set to `_blank` or to `_self`)
Injects CSS into the `InAppBrowser` window.
```dart
inAppBrowser.injectStyleCode(String source);
......@@ -403,7 +464,7 @@ inAppBrowser.injectStyleCode(String source);
#### Future\<void\> InAppBrowser.injectStyleFile
Injects a CSS file into the `InAppBrowser` window. (Only available when the target is set to `_blank` or to `_self`)
Injects a CSS file into the `InAppBrowser` window.
```dart
inAppBrowser.injectStyleFile(String urlFile);
......
......@@ -2,10 +2,11 @@ package com.pichillilorenzo.flutter_inappbrowser;
public class InAppBrowserOptions extends Options {
final static String LOG_TAG = "InAppBrowserOptions";
static final String LOG_TAG = "InAppBrowserOptions";
public boolean useShouldOverrideUrlLoading = false;
public boolean useOnLoadResource = false;
public boolean openWithSystemBrowser = false;
public boolean clearCache = false;
public String userAgent = "";
public boolean javaScriptEnabled = true;
......@@ -16,6 +17,7 @@ public class InAppBrowserOptions extends Options {
public String toolbarTopFixedTitle = "";
public boolean hideUrlBar = false;
public boolean mediaPlaybackRequiresUserGesture = true;
public boolean isLocalFile = false;
public boolean hideTitleBar = false;
public boolean closeOnCannotGoBack = true;
......
......@@ -20,7 +20,7 @@ public class InAppBrowserWebChromeClient extends WebChromeClient {
private WebViewActivity activity;
private ValueCallback<Uri[]> mUploadMessageArray;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
private final static int FILECHOOSER_RESULTCODE = 1;
public InAppBrowserWebChromeClient(WebViewActivity activity) {
super();
......@@ -45,8 +45,7 @@ public class InAppBrowserWebChromeClient extends WebChromeClient {
activity.progressBar.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
activity.progressBar.setProgress(progress, true);
}
else {
} else {
activity.progressBar.setProgress(progress);
}
if (progress == 100) {
......@@ -77,12 +76,12 @@ public class InAppBrowserWebChromeClient extends WebChromeClient {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
activity.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
activity.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
......@@ -93,20 +92,20 @@ public class InAppBrowserWebChromeClient extends WebChromeClient {
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
activity.startActivityForResult( Intent.createChooser( i, "File Chooser" ), FILECHOOSER_RESULTCODE );
activity.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
//For Android 5.0+
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
FileChooserParams fileChooserParams){
if(mUploadMessageArray != null){
FileChooserParams fileChooserParams) {
if (mUploadMessageArray != null) {
mUploadMessageArray.onReceiveValue(null);
}
mUploadMessageArray = filePathCallback;
......
......@@ -23,6 +23,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.flutter.plugin.common.MethodChannel;
import okhttp3.Request;
import okhttp3.Response;
......@@ -106,8 +107,7 @@ public class InAppBrowserWebViewClient extends WebViewClient {
} 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:")) {
} 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));
......@@ -180,7 +180,6 @@ public class InAppBrowserWebViewClient extends WebViewClient {
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
......@@ -201,6 +200,10 @@ public class InAppBrowserWebViewClient extends WebViewClient {
view.evaluateJavascript(WebViewActivity.consoleLogJS, null);
view.evaluateJavascript(JavaScriptBridgeInterface.flutterInAppBroserJSClass, null);
}
else {
view.loadUrl("javascript:"+WebViewActivity.consoleLogJS);
view.loadUrl("javascript:"+JavaScriptBridgeInterface.flutterInAppBroserJSClass);
}
Map<String, Object> obj = new HashMap<>();
obj.put("uuid", activity.uuid);
......@@ -221,7 +224,7 @@ public class InAppBrowserWebViewClient extends WebViewClient {
InAppBrowserFlutterPlugin.channel.invokeMethod("onLoadError", obj);
}
public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
Map<String, Object> obj = new HashMap<>();
......@@ -267,7 +270,7 @@ public class InAppBrowserWebViewClient extends WebViewClient {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request){
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (!request.getMethod().toLowerCase().equals("get") || !activity.options.useOnLoadResource) {
return null;
......@@ -281,6 +284,7 @@ public class InAppBrowserWebViewClient extends WebViewClient {
long startResourceTime = System.currentTimeMillis();
Response response = activity.httpClient.newCall(mRequest).execute();
long startTime = startResourceTime - startPageTime;
startTime = (startTime < 0) ? 0 : startTime;
long duration = System.currentTimeMillis() - startResourceTime;
if (response.cacheResponse() != null) {
......@@ -296,8 +300,8 @@ public class InAppBrowserWebViewClient extends WebViewClient {
Map<String, String> headersResponse = new HashMap<String, String>();
for (Map.Entry<String, List<String>> entry : response.headers().toMultimap().entrySet()) {
StringBuilder value = new StringBuilder();
for (String val: entry.getValue()) {
value.append( (value.toString().isEmpty()) ? val : "; " + val );
for (String val : entry.getValue()) {
value.append((value.toString().isEmpty()) ? val : "; " + val);
}
headersResponse.put(entry.getKey().toLowerCase(), value.toString());
}
......@@ -305,8 +309,8 @@ public class InAppBrowserWebViewClient extends WebViewClient {
Map<String, String> headersRequest = new HashMap<String, String>();
for (Map.Entry<String, List<String>> entry : mRequest.headers().toMultimap().entrySet()) {
StringBuilder value = new StringBuilder();
for (String val: entry.getValue()) {
value.append( (value.toString().isEmpty()) ? val : "; " + val );
for (String val : entry.getValue()) {
value.append((value.toString().isEmpty()) ? val : "; " + val);
}
headersRequest.put(entry.getKey().toLowerCase(), value.toString());
}
......
......@@ -10,9 +10,9 @@ public class JavaScriptBridgeInterface {
static final String name = "flutter_inappbrowser";
WebViewActivity activity;
static final String flutterInAppBroserJSClass = "window." + name + ".callHandler = function(handlerName, ...args) {\n" +
"window." + name + "._callHandler(handlerName, JSON.stringify(args));\n" +
"}\n";
static final String flutterInAppBroserJSClass = "window." + name + ".callHandler = function(handlerName, ...args) {" +
"window." + name + "._callHandler(handlerName, JSON.stringify(args));" +
"}";
JavaScriptBridgeInterface(WebViewActivity a) {
activity = a;
......
......@@ -9,12 +9,12 @@ import java.util.HashMap;
public class Options {
final static String LOG_TAG = "";
static String LOG_TAG = "";
public void parse(HashMap<String, Object> options) {
public Options parse(HashMap<String, Object> options) {
Iterator it = options.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> pair = (Map.Entry<String, Object>)it.next();
Map.Entry<String, Object> pair = (Map.Entry<String, Object>) it.next();
try {
this.getClass().getDeclaredField(pair.getKey()).set(this, pair.getValue());
} catch (NoSuchFieldException e) {
......@@ -23,11 +23,12 @@ public class Options {
Log.d(LOG_TAG, e.getMessage());
}
}
return this;
}
public HashMap<String, Object> getHashMap() {
HashMap<String, Object> options = new HashMap<>();
for (Field f: this.getClass().getDeclaredFields()) {
for (Field f : this.getClass().getDeclaredFields()) {
try {
options.put(f.getName(), f.get(this));
} catch (IllegalAccessException e) {
......
......@@ -41,31 +41,31 @@ public class WebViewActivity extends AppCompatActivity {
public boolean isHidden = false;
OkHttpClient httpClient;
static final String consoleLogJS = "(function() {\n"+
" var oldLogs = {\n"+
" 'log': console.log,\n"+
" 'debug': console.debug,\n"+
" 'error': console.error,\n"+
" 'info': console.info,\n"+
" 'warn': console.warn\n"+
" };\n"+
" for (var k in oldLogs) {\n"+
" (function(oldLog) {\n"+
" console[oldLog] = function() {\n"+
" var message = ''\n"+
" for (var i in arguments) {\n"+
" if (message == '') {\n"+
" message += arguments[i];\n"+
" }\n"+
" else {\n"+
" message += ' ' + arguments[i];\n"+
" }\n"+
" }\n"+
" oldLogs[oldLog].call(console, message);\n"+
" }\n"+
" })(k);\n"+
" }\n"+
"})();";
static final String consoleLogJS = "(function() {" +
" var oldLogs = {" +
" 'log': console.log," +
" 'debug': console.debug," +
" 'error': console.error," +
" 'info': console.info," +
" 'warn': console.warn" +
" };" +
" for (var k in oldLogs) {" +
" (function(oldLog) {" +
" console[oldLog] = function() {" +
" var message = '';" +
" for (var i in arguments) {" +
" if (message == '') {" +
" message += arguments[i];" +
" }" +
" else {" +
" message += ' ' + arguments[i];" +
" }" +
" }" +
" oldLogs[oldLog].call(console, message);" +
" }" +
" })(k);" +
" }" +
"})();";
@Override
protected void onCreate(Bundle savedInstanceState) {
......@@ -94,7 +94,7 @@ public class WebViewActivity extends AppCompatActivity {
httpClient = new OkHttpClient().newBuilder().cache(new Cache(getApplicationContext().getCacheDir(), cacheSize)).build();
webView.loadUrl(url, headers);
//webView.loadData("<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Document</title> </head> <body> ciao <img src=\"https://via.placeholder.com/350x150\" /> <img src=\"./images/test\" alt=\"not found\" /></body> </html>", "text/html", "utf8");
//webView.loadData("<!DOCTYPE assets> <assets lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Document</title> </head> <body> ciao <img src=\"https://via.placeholder.com/350x150\" /> <img src=\"./images/test\" alt=\"not found\" /></body> </assets>", "text/assets", "utf8");
}
......@@ -170,7 +170,7 @@ public class WebViewActivity extends AppCompatActivity {
// Enable Thirdparty Cookies on >=Android 5.0 device
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
CookieManager.getInstance().setAcceptThirdPartyCookies(webView,true);
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(options.useWideViewPort);
......@@ -256,20 +256,34 @@ public class WebViewActivity extends AppCompatActivity {
return true;
}
public void loadUrl (String url, MethodChannel.Result result) {
public void loadUrl(String url, MethodChannel.Result result) {
if (webView != null && !url.isEmpty()) {
webView.loadUrl(url);
}
else {
} else {
result.error("Cannot load url", "", null);
}
}
public void loadUrl (String url, Map<String, String> headers, MethodChannel.Result result) {
public void loadUrl(String url, Map<String, String> headers, MethodChannel.Result result) {
if (webView != null && !url.isEmpty()) {
webView.loadUrl(url, headers);
} else {
result.error("Cannot load url", "", null);
}
}
else {
public void loadFile(String url, MethodChannel.Result result) {
if (webView != null && !url.isEmpty()) {
webView.loadUrl(url);
} else {
result.error("Cannot load url", "", null);
}
}
public void loadFile(String url, Map<String, String> headers, MethodChannel.Result result) {
if (webView != null && !url.isEmpty()) {
webView.loadUrl(url, headers);
} else {
result.error("Cannot load url", "", null);
}
}
......@@ -279,7 +293,7 @@ public class WebViewActivity extends AppCompatActivity {
if (canGoBack())
goBack();
else if (options.closeOnCannotGoBack)
InAppBrowserFlutterPlugin.close(uuid);
InAppBrowserFlutterPlugin.close(uuid, null);
return true;
}
return super.onKeyDown(keyCode, event);
......@@ -319,6 +333,7 @@ public class WebViewActivity extends AppCompatActivity {
openActivity.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivityIfNeeded(openActivity, 0);
}
public void show() {
isHidden = false;
Intent openActivity = new Intent(InAppBrowserFlutterPlugin.registrar.activity(), WebViewActivity.class);
......@@ -326,7 +341,7 @@ public class WebViewActivity extends AppCompatActivity {
startActivityIfNeeded(openActivity, 0);
}
public void stopLoading(){
public void stopLoading() {
if (webView != null)
webView.stopLoading();
}
......@@ -376,7 +391,7 @@ public class WebViewActivity extends AppCompatActivity {
}
public void closeButtonClicked(MenuItem item) {
InAppBrowserFlutterPlugin.close(uuid);
InAppBrowserFlutterPlugin.close(uuid, null);
}
}
......@@ -19,11 +19,8 @@ public class ChromeCustomTabsActivity extends Activity {
protected static final String LOG_TAG = "CustomTabsActivity";
String uuid;
String uuidFallback;
CustomTabsIntent.Builder builder;
ChromeCustomTabsOptions options;
Map<String, String> headersFallback;
InAppBrowserOptions optionsFallback;
private CustomTabActivityHelper customTabActivityHelper;
private final int CHROME_CUSTOM_TAB_REQUEST_CODE = 100;
......@@ -34,18 +31,13 @@ public class ChromeCustomTabsActivity extends Activity {
setContentView(R.layout.chrome_custom_tabs_layout);
Bundle b = getIntent().getExtras();
assert b != null;
uuid = b.getString("uuid");
uuidFallback = b.getString("uuidFallback");
String url = b.getString("url");
options = new ChromeCustomTabsOptions();
options.parse((HashMap<String, Object>) b.getSerializable("options"));
headersFallback = (HashMap<String, String>) b.getSerializable("headers");
optionsFallback = new InAppBrowserOptions();
optionsFallback.parse((HashMap<String, Object>) b.getSerializable("optionsFallback"));
InAppBrowserFlutterPlugin.chromeCustomTabsActivities.put(uuid, this);
customTabActivityHelper = new CustomTabActivityHelper();
......@@ -55,26 +47,13 @@ public class ChromeCustomTabsActivity extends Activity {
CustomTabsIntent customTabsIntent = builder.build();
boolean chromeCustomTabsOpened = customTabActivityHelper.openCustomTab(this, customTabsIntent, Uri.parse(url), CHROME_CUSTOM_TAB_REQUEST_CODE,
new CustomTabActivityHelper.CustomTabFallback() {
@Override
public void openUri(Activity activity, Uri uri) {
if (!uuidFallback.isEmpty())
InAppBrowserFlutterPlugin.open(uuidFallback, null, uri.toString(), optionsFallback, headersFallback, false, null);
else {
Log.d(LOG_TAG, "No WebView fallback declared.");
activity.finish();
}
}
});
CustomTabActivityHelper.openCustomTab(this, customTabsIntent, Uri.parse(url), CHROME_CUSTOM_TAB_REQUEST_CODE);
if (chromeCustomTabsOpened) {
Map<String, Object> obj = new HashMap<>();
obj.put("uuid", uuid);
InAppBrowserFlutterPlugin.channel.invokeMethod("onChromeSafariBrowserOpened", obj);
InAppBrowserFlutterPlugin.channel.invokeMethod("onChromeSafariBrowserLoaded", obj);
}
}
private void prepareCustomTabs() {
if (options.addShareButton)
......
......@@ -27,26 +27,13 @@ public class CustomTabActivityHelper implements ServiceConnectionCallback {
* @param activity The host activity.
* @param customTabsIntent a CustomTabsIntent to be used if Custom Tabs is available.
* @param uri the Uri to be opened.
* @param fallback a CustomTabFallback to be used if Custom Tabs is not available.
*/
public static boolean openCustomTab(Activity activity,
public static void openCustomTab(Activity activity,
CustomTabsIntent customTabsIntent,
Uri uri,
int requestCode,
CustomTabFallback fallback) {
//If we cant find a package name, it means theres no browser that supports
//Chrome Custom Tabs installed. So, we fallback to the webview
if (!isAvailable(activity)) {
if (fallback != null) {
fallback.openUri(activity, uri);
}
} else {
//customTabsIntent.intent.setPackage(packageName);
int requestCode) {
customTabsIntent.intent.setData(uri);
activity.startActivityForResult(customTabsIntent.intent, requestCode);
return true;
}
return false;
}
public static boolean isAvailable(Activity activity) {
......@@ -144,16 +131,4 @@ public class CustomTabActivityHelper implements ServiceConnectionCallback {
void onCustomTabsDisconnected();
}
/**
* To be used as a fallback to open the Uri when Custom Tabs is not available.
*/
public interface CustomTabFallback {
/**
*
* @param activity The Activity that wants to open the Uri.
* @param uri The uri to be opened by the fallback.
*/
void openUri(Activity activity, Uri uri);
}
}
\ No newline at end of file
body {
background-color: #333;
color: #fff;
}
img {
max-width: 100%;
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 439 137.29" enable-background="new 0 0 439 137.29" xml:space="preserve">
<g>
<g opacity="0.54">
<path d="M207.08,20.2h27.55c9.35,0,17.51,1.93,24.49,5.8c6.97,3.87,12.33,9.25,16.07,16.13c3.74,6.89,5.61,14.79,5.61,23.72
s-1.87,16.83-5.61,23.72s-9.1,12.26-16.07,16.13c-6.97,3.87-15.13,5.8-24.49,5.8h-27.55V20.2z M234.63,101.19
c10.8,0,19.36-3.1,25.7-9.31c6.33-6.21,9.5-14.88,9.5-26.02s-3.17-19.81-9.5-26.02c-6.33-6.21-14.9-9.31-25.7-9.31H217.8v70.65
h16.83V101.19z"/>
<path d="M297.49,110.75c-3.74-1.87-6.63-4.44-8.67-7.72c-2.04-3.27-3.06-6.99-3.06-11.16c0-6.89,2.59-12.26,7.78-16.13
c5.18-3.87,11.73-5.8,19.64-5.8c3.91,0,7.54,0.43,10.9,1.28s5.93,1.83,7.72,2.93V70.2c0-4.85-1.7-8.74-5.1-11.67
c-3.4-2.93-7.7-4.4-12.88-4.4c-3.66,0-7.01,0.79-10.08,2.36c-3.06,1.57-5.48,3.76-7.27,6.57l-8.16-6.12
c2.55-3.91,6.06-6.97,10.52-9.18c4.46-2.21,9.42-3.32,14.86-3.32c8.84,0,15.79,2.32,20.85,6.95c5.06,4.64,7.59,10.95,7.59,18.94
v41.19H331.8v-9.31h-0.51c-1.87,3.15-4.68,5.82-8.42,8.03c-3.74,2.21-7.95,3.32-12.63,3.32
C305.49,113.56,301.24,112.62,297.49,110.75z M321.47,101.19c3.14-1.87,5.65-4.38,7.52-7.52s2.81-6.59,2.81-10.33
c-2.04-1.36-4.55-2.47-7.52-3.32c-2.98-0.85-6.12-1.28-9.44-1.28c-5.95,0-10.44,1.23-13.45,3.7c-3.02,2.47-4.53,5.66-4.53,9.56
c0,3.57,1.36,6.46,4.08,8.67c2.72,2.21,6.16,3.32,10.33,3.32C314.92,103.99,318.33,103.06,321.47,101.19z"/>
<path d="M353.57,47.5h10.33v10.33h0.51c1.53-3.83,4.12-6.8,7.78-8.93c3.65-2.12,7.65-3.19,11.99-3.19c1.87,0,3.44,0.13,4.72,0.38
v11.1c-1.45-0.34-3.4-0.51-5.87-0.51c-5.53,0-10.01,1.83-13.45,5.48c-3.44,3.66-5.17,8.42-5.17,14.28v36.09h-10.84V47.5
L353.57,47.5z M420.89,112.26c-2.25-0.86-4.14-2.03-5.68-3.51c-1.7-1.64-2.98-3.55-3.83-5.71c-0.85-2.16-1.28-4.8-1.28-7.92V56.3
h-11.35v-9.82h11.35V28.12h10.84v18.36h15.81v9.82h-15.81v36.24c0,3.65,0.68,6.34,2.04,8.08c1.61,1.91,3.95,2.87,7.01,2.87
c2.46,0,4.85-0.72,7.14-2.17v10.59c-1.28,0.59-2.57,1.02-3.89,1.28s-3,0.38-5.04,0.38C425.59,113.56,423.15,113.12,420.89,112.26z
"/>
</g>
<g>
<path fill="#01579B" d="M29.64,108.94L6.36,85.66c-2.76-2.84-4.48-6.84-4.48-10.75c0-1.81,1.02-4.64,1.79-6.27l21.49-44.77
L29.64,108.94z"/>
<path fill="#40C4FF" d="M109.34,28.35L86.06,5.07c-2.03-2.04-6.27-4.48-9.85-4.48c-3.08,0-6.1,0.62-8.06,1.79L25.17,23.87
L109.34,28.35z"/>
<polygon fill="#40C4FF" points="57.4,136.7 113.82,136.7 113.82,112.52 71.73,99.09 33.23,112.52 "/>
<path fill="#29B6F6" d="M25.17,96.41c0,7.18,0.9,8.95,4.48,12.54l3.58,3.58h80.59l-39.4-44.77L25.17,23.88V96.41z"/>
<path fill="#01579B" d="M96.8,23.87H25.16l88.65,88.65h24.18V57l-28.65-28.65C105.32,24.31,101.74,23.87,96.8,23.87z"/>
<path opacity="0.2" fill="#FFFFFF" enable-background="new " d="M30.54,109.84c-3.58-3.6-4.48-7.14-4.48-13.43V24.77l-0.9-0.9
V96.4C25.17,102.7,25.17,104.44,30.54,109.84l2.69,2.69l0,0L30.54,109.84z"/>
<polygon opacity="0.2" fill="#263238" enable-background="new " points="137.1,56.11 137.1,111.63 112.92,111.63
113.82,112.52 138,112.52 138,57.01 "/>
<path opacity="0.2" fill="#FFFFFF" enable-background="new " d="M109.34,28.35c-4.44-4.44-8.08-4.48-13.43-4.48H25.17l0.9,0.9
h69.85C98.58,24.77,105.33,24.32,109.34,28.35L109.34,28.35z"/>
<radialGradient id="SVGID_1_" cx="69.955" cy="60.8864" r="68.065" gradientTransform="matrix(1 0 0 -1 0 129.5328)" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color:#FFFFFF;stop-opacity:0.1"/>
<stop offset="1" style="stop-color:#FFFFFF;stop-opacity:0"/>
</radialGradient>
<path opacity="0.2" fill="url(#SVGID_1_)" enable-background="new " d="M137.1,56.11l-27.76-27.76L86.06,5.07
c-2.03-2.04-6.27-4.48-9.85-4.48c-3.08,0-6.1,0.62-8.06,1.79L25.17,23.87L3.68,68.64c-0.77,1.63-1.79,4.46-1.79,6.27
c0,3.91,1.72,7.91,4.48,10.75l21.46,21.3c0.51,0.63,1.11,1.27,1.83,1.98l0.9,0.9l2.69,2.69l23.28,23.28l0.9,0.9h55.52h0.9v-24.18
h24.18v-0.06V57.01L137.1,56.11z"/>
</g>
</g>
</svg>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="container">
<img src="images/dart.svg" alt="dart logo">
<div class="row">
<div class="col-sm">
One of three columns
</div>
<div class="col-sm">
One of three columns
</div>
<div class="col-sm">
One of three columns
</div>
</div>
</div>
<script>
console.log("hello");
</script>
</div>
</body>
</html>
\ No newline at end of file
......@@ -2,6 +2,11 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
......
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';
class MyInAppBrowser extends InAppBrowser {
@override
Future onLoadStart(String url) async {
print("\n\nStarted $url\n\n");
......@@ -13,6 +13,8 @@ class MyInAppBrowser extends InAppBrowser {
Future onLoadStop(String url) async {
print("\n\nStopped $url\n\n");
//print("\n\n ${await this.isHidden()} \n\n");
// await this.injectScriptCode("window.flutter_inappbrowser.callHandler('handlerTest', 1, 5,'string', {'key': 5}, [4,6,8]);");
// await this.injectScriptCode("window.flutter_inappbrowser.callHandler('handlerTest2', false, null, undefined);");
// await this.injectScriptCode("setTimeout(function(){window.flutter_inappbrowser.callHandler('handlerTest', 'anotherString');}, 1000);");
......@@ -40,8 +42,7 @@ class MyInAppBrowser extends InAppBrowser {
// var x = {"as":4, "dfdfg": 6};
// x;
// """));
//print("\n\n ${await this.isHidden()} \n\n");
//
// await this.injectScriptFile("https://code.jquery.com/jquery-3.3.1.min.js");
// this.injectScriptCode("""
// \$( "body" ).html( "Next Step..." )
......@@ -73,29 +74,33 @@ class MyInAppBrowser extends InAppBrowser {
}
@override
void onLoadResource(WebResourceResponse response, WebResourceRequest request) {
print("Started at: " + response.startTime.toString() + "ms ---> duration: " + response.duration.toString() + "ms " + response.url);
void onLoadResource(
WebResourceResponse response, WebResourceRequest request) {
print("Started at: " +
response.startTime.toString() +
"ms ---> duration: " +
response.duration.toString() +
"ms " +
response.url);
// if (response.headers["content-length"] != null)
// print(response.headers["content-length"] + " length");
}
@override
void onConsoleMessage(ConsoleMessage consoleMessage) {
// print("""
// console output:
// sourceURL: ${consoleMessage.sourceURL}
// lineNumber: ${consoleMessage.lineNumber}
// message: ${consoleMessage.message}
// messageLevel: ${consoleMessage.messageLevel}
// """);
print("""
console output:
sourceURL: ${consoleMessage.sourceURL}
lineNumber: ${consoleMessage.lineNumber}
message: ${consoleMessage.message}
messageLevel: ${consoleMessage.messageLevel}
""");
}
}
MyInAppBrowser inAppBrowserFallback = new MyInAppBrowser();
class MyChromeSafariBrowser extends ChromeSafariBrowser {
MyChromeSafariBrowser(browserFallback) : super(browserFallback);
@override
......@@ -115,9 +120,10 @@ class MyChromeSafariBrowser extends ChromeSafariBrowser {
}
// adding a webview fallback
MyChromeSafariBrowser chromeSafariBrowser = new MyChromeSafariBrowser(inAppBrowserFallback);
MyChromeSafariBrowser chromeSafariBrowser =
new MyChromeSafariBrowser(inAppBrowserFallback);
void main() {
Future main() async {
runApp(new MyApp());
}
......@@ -127,11 +133,11 @@ class MyApp extends StatefulWidget {
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
// int indexTest = inAppBrowserFallback.addJavaScriptHandler("handlerTest", (arguments) async {
// int indexTest = inAppBrowserFallback.addJavaScriptHandler("handlerTest",
// (arguments) async {
// print("handlerTest arguments");
// print(arguments);
// });
......@@ -150,10 +156,14 @@ class _MyAppState extends State<MyApp> {
title: const Text('Flutter InAppBrowser Plugin example app'),
),
body: new Center(
child: new RaisedButton(onPressed: () {
//chromeSafariBrowser.open("https://flutter.io/");
inAppBrowserFallback.open(url: "https://flutter.io/", options: {
//"useOnLoadResource": true,
child: new RaisedButton(
onPressed: () async {
// await chromeSafariBrowser.open("https://flutter.io/");
// await InAppBrowser.openWithSystemBrowser("https://flutter.io/");
await inAppBrowserFallback.openOnLocalhost("assets/index.html", options: {
"useOnLoadResource": true,
//"hidden": true,
//"toolbarTopFixedTitle": "Fixed title",
//"useShouldOverrideUrlLoading": true
......@@ -162,9 +172,29 @@ class _MyAppState extends State<MyApp> {
//"toolbarBottom": false
});
// await inAppBrowserFallback.open(url: "assets/index.html", options: {
// "isLocalFile": true,
// "useOnLoadResource": true,
// //"hidden": true,
// //"toolbarTopFixedTitle": "Fixed title",
// //"useShouldOverrideUrlLoading": true
// //"hideUrlBar": true,
// //"toolbarTop": false,
// //"toolbarBottom": false
// });
// await inAppBrowserFallback.open(url: "https://flutter.io/", options: {
// //"useOnLoadResource": true,
// //"hidden": true,
// //"toolbarTopFixedTitle": "Fixed title",
// //"useShouldOverrideUrlLoading": true
// //"hideUrlBar": true,
// //"toolbarTop": false,
// //"toolbarBottom": false
// });
//await inAppBrowserFallback.openOnLocalhost("assets/index.html");
},
child: Text("Open InAppBrowser")
),
child: Text("Open InAppBrowser")),
),
),
);
......
......@@ -38,6 +38,11 @@ flutter:
# the material Icons class.
uses-material-design: true
assets:
- assets/index.html
- assets/css/
- assets/images/
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
......
......@@ -14,6 +14,12 @@
<excludeFolder url="file://$MODULE_DIR$/example/flutter_plugin/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/example/flutter_plugin/.pub" />
<excludeFolder url="file://$MODULE_DIR$/example/flutter_plugin/build" />
<excludeFolder url="file://$MODULE_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/.pub" />
<excludeFolder url="file://$MODULE_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/build" />
<excludeFolder url="file://$MODULE_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/example/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/example/.pub" />
<excludeFolder url="file://$MODULE_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/example/build" />
<excludeFolder url="file://$MODULE_DIR$/example/ios/Flutter/flutter_assets/packages" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
......
......@@ -12,6 +12,7 @@ public class InAppBrowserOptions: Options {
var useShouldOverrideUrlLoading = false
var useOnLoadResource = false
var openWithSystemBrowser = false;
var clearCache = false
var userAgent = ""
var javaScriptEnabled = true
......@@ -21,6 +22,7 @@ public class InAppBrowserOptions: Options {
var toolbarTopBackgroundColor = ""
var hideUrlBar = false
var mediaPlaybackRequiresUserGesture = true
var isLocalFile = false
var disallowOverScroll = false
var toolbarBottom = true
......
......@@ -81,7 +81,6 @@ func convertToDictionary(text: String) -> [String: Any]? {
return nil
}
//extension WKWebView{
//
// var keyboardDisplayRequiresUserAction: Bool? {
......@@ -139,6 +138,7 @@ class WKWebView_IBWrapper: WKWebView {
}
class InAppBrowserWebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate, UITextFieldDelegate, WKScriptMessageHandler {
@IBOutlet var webView: WKWebView_IBWrapper!
@IBOutlet var closeButton: UIButton!
@IBOutlet var reloadButton: UIBarButtonItem!
......@@ -421,11 +421,7 @@ class InAppBrowserWebViewController: UIViewController, WKUIDelegate, WKNavigatio
}
@objc func close() {
currentURL = nil
if (navigationDelegate != nil) {
navigationDelegate?.browserExit(uuid: self.uuid)
}
//currentURL = nil
weak var weakSelf = self
......@@ -435,12 +431,18 @@ class InAppBrowserWebViewController: UIViewController, WKUIDelegate, WKNavigatio
weakSelf?.presentingViewController?.dismiss(animated: true, completion: {() -> Void in
self.tmpWindow?.windowLevel = 0.0
UIApplication.shared.delegate?.window??.makeKeyAndVisible()
if (self.navigationDelegate != nil) {
self.navigationDelegate?.browserExit(uuid: self.uuid)
}
})
}
else {
weakSelf?.parent?.dismiss(animated: true, completion: {() -> Void in
self.tmpWindow?.windowLevel = 0.0
UIApplication.shared.delegate?.window??.makeKeyAndVisible()
if (self.navigationDelegate != nil) {
self.navigationDelegate?.browserExit(uuid: self.uuid)
}
})
}
})
......@@ -527,7 +529,9 @@ class InAppBrowserWebViewController: UIViewController, WKUIDelegate, WKNavigatio
}
if navigationAction.navigationType == .linkActivated && (browserOptions?.useShouldOverrideUrlLoading)! {
if navigationDelegate != nil {
navigationDelegate?.shouldOverrideUrlLoading(uuid: self.uuid, webView: webView, url: url)
}
decisionHandler(.cancel)
return
}
......@@ -606,7 +610,9 @@ class InAppBrowserWebViewController: UIViewController, WKUIDelegate, WKNavigatio
spinner.startAnimating()
}
return (navigationDelegate?.onLoadStart(uuid: self.uuid, webView: webView))!
if navigationDelegate != nil {
navigationDelegate?.onLoadStart(uuid: self.uuid, webView: webView)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
......@@ -617,8 +623,11 @@ class InAppBrowserWebViewController: UIViewController, WKUIDelegate, WKNavigatio
backButton.isEnabled = webView.canGoBack
forwardButton.isEnabled = webView.canGoForward
spinner.stopAnimating()
if navigationDelegate != nil {
navigationDelegate?.onLoadStop(uuid: self.uuid, webView: webView)
}
}
func webView(_ view: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
......@@ -627,16 +636,20 @@ class InAppBrowserWebViewController: UIViewController, WKUIDelegate, WKNavigatio
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("webView:didFailNavigationWithError - \(Int(error._code)): \(error.localizedDescription)")
backButton.isEnabled = webView.canGoBack
forwardButton.isEnabled = webView.canGoForward
spinner.stopAnimating()
if navigationDelegate != nil {
navigationDelegate?.onLoadError(uuid: self.uuid, webView: webView, error: error)
}
}
func didReceiveResourceResponse(_ response: URLResponse, fromRequest request: URLRequest?, withData data: Data, startTime: Int, duration: Int) {
if navigationDelegate != nil {
navigationDelegate?.onLoadResource(uuid: self.uuid, webView: webView, response: response, fromRequest: request, withData: data, startTime: startTime, duration: duration)
}
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name.starts(with: "console") {
......@@ -663,8 +676,10 @@ class InAppBrowserWebViewController: UIViewController, WKUIDelegate, WKNavigatio
messageLevel = "LOG"
break;
}
if navigationDelegate != nil {
navigationDelegate?.onConsoleMessage(uuid: self.uuid, sourceURL: "", lineNumber: 1, message: message.body as! String, messageLevel: messageLevel)
}
}
else if message.name == "resourceLoaded" {
if let resource = convertToDictionary(text: message.body as! String) {
let url = URL(string: resource["name"] as! String)!
......@@ -695,7 +710,9 @@ class InAppBrowserWebViewController: UIViewController, WKUIDelegate, WKNavigatio
let body = message.body as! [String: Any]
let handlerName = body["handlerName"] as! String
let args = body["args"] as! String
if navigationDelegate != nil {
self.navigationDelegate?.onCallJsHandler(uuid: self.uuid, webView: webView, handlerName: handlerName, args: args)
}
}
}
}
......@@ -14,12 +14,13 @@ public class Options: NSObject {
super.init()
}
public func parse(options: [String: Any]) {
public func parse(options: [String: Any]) -> Options {
for (key, value) in options {
if self.responds(to: Selector(key)) {
self.setValue(value, forKey: key)
}
}
return self
}
}
......@@ -40,15 +40,15 @@ class SafariViewController: SFSafariViewController, SFSafariViewControllerDelega
}
func close() {
if (statusDelegate != nil) {
statusDelegate?.safariExit(uuid: self.uuid)
}
dismiss(animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(400), execute: {() -> Void in
self.tmpWindow?.windowLevel = 0.0
UIApplication.shared.delegate?.window??.makeKeyAndVisible()
if (self.statusDelegate != nil) {
self.statusDelegate?.safariExit(uuid: self.uuid)
}
})
}
......
This diff is collapsed.
This diff is collapsed.
name: flutter_inappbrowser
description: A Flutter plugin that allows you to open an in-app browser window. (inspired by the popular cordova-plugin-inappbrowser).
version: 0.3.2
version: 0.4.0
author: Lorenzo Pichilli <pichillilorenzo@gmail.com>
homepage: https://github.com/pichillilorenzo/flutter_inappbrowser
......@@ -11,6 +11,7 @@ dependencies:
flutter:
sdk: flutter
uuid: ^1.0.3
mime: ^0.9.6+2
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment