add recommend books around me
@@ -55,6 +55,13 @@ module.exports = [
|
||||
"merges": [
|
||||
"navigator.notification"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "plugins/org.apache.cordova.inappbrowser/www/InAppBrowser.js",
|
||||
"id": "org.apache.cordova.inappbrowser.InAppBrowser",
|
||||
"clobbers": [
|
||||
"window.open"
|
||||
]
|
||||
}
|
||||
];
|
||||
module.exports.metadata =
|
||||
@@ -64,7 +71,8 @@ module.exports.metadata =
|
||||
"org.apache.cordova.device": "0.2.7",
|
||||
"org.apache.cordova.geolocation": "0.3.5",
|
||||
"org.apache.cordova.dialogs": "0.2.6",
|
||||
"org.apache.cordova.vibration": "0.3.7"
|
||||
"org.apache.cordova.vibration": "0.3.7",
|
||||
"org.apache.cordova.inappbrowser": "0.3.1"
|
||||
}
|
||||
// BOTTOM OF METADATA
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
cordova.define("org.apache.cordova.inappbrowser.InAppBrowser", function(require, exports, module) { /*
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
var exec = require('cordova/exec');
|
||||
var channel = require('cordova/channel');
|
||||
var modulemapper = require('cordova/modulemapper');
|
||||
var urlutil = require('cordova/urlutil');
|
||||
|
||||
function InAppBrowser() {
|
||||
this.channels = {
|
||||
'loadstart': channel.create('loadstart'),
|
||||
'loadstop' : channel.create('loadstop'),
|
||||
'loaderror' : channel.create('loaderror'),
|
||||
'exit' : channel.create('exit')
|
||||
};
|
||||
}
|
||||
|
||||
InAppBrowser.prototype = {
|
||||
_eventHandler: function (event) {
|
||||
if (event.type in this.channels) {
|
||||
this.channels[event.type].fire(event);
|
||||
}
|
||||
},
|
||||
close: function (eventname) {
|
||||
exec(null, null, "InAppBrowser", "close", []);
|
||||
},
|
||||
show: function (eventname) {
|
||||
exec(null, null, "InAppBrowser", "show", []);
|
||||
},
|
||||
addEventListener: function (eventname,f) {
|
||||
if (eventname in this.channels) {
|
||||
this.channels[eventname].subscribe(f);
|
||||
}
|
||||
},
|
||||
removeEventListener: function(eventname, f) {
|
||||
if (eventname in this.channels) {
|
||||
this.channels[eventname].unsubscribe(f);
|
||||
}
|
||||
},
|
||||
|
||||
executeScript: function(injectDetails, cb) {
|
||||
if (injectDetails.code) {
|
||||
exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
|
||||
} else if (injectDetails.file) {
|
||||
exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
|
||||
} else {
|
||||
throw new Error('executeScript requires exactly one of code or file to be specified');
|
||||
}
|
||||
},
|
||||
|
||||
insertCSS: function(injectDetails, cb) {
|
||||
if (injectDetails.code) {
|
||||
exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
|
||||
} else if (injectDetails.file) {
|
||||
exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
|
||||
} else {
|
||||
throw new Error('insertCSS requires exactly one of code or file to be specified');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = function(strUrl, strWindowName, strWindowFeatures) {
|
||||
// Don't catch calls that write to existing frames (e.g. named iframes).
|
||||
if (window.frames && window.frames[strWindowName]) {
|
||||
var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
|
||||
return origOpenFunc.apply(window, arguments);
|
||||
}
|
||||
|
||||
strUrl = urlutil.makeAbsolute(strUrl);
|
||||
var iab = new InAppBrowser();
|
||||
var cb = function(eventname) {
|
||||
iab._eventHandler(eventname);
|
||||
};
|
||||
|
||||
exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
|
||||
return iab;
|
||||
};
|
||||
|
||||
|
||||
});
|
||||
@@ -33,6 +33,7 @@
|
||||
0F97F9F0F6884BEE9E6014E2 /* CDVNotification.m in Sources */ = {isa = PBXBuildFile; fileRef = 784FE9E354CA4B52B5B71807 /* CDVNotification.m */; };
|
||||
D944CA2667DF41AD8C037F9D /* CDVNotification.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 5D9C1FE54F5040609267B2C0 /* CDVNotification.bundle */; };
|
||||
46F5C9534FF04371A003E27C /* CDVVibration.m in Sources */ = {isa = PBXBuildFile; fileRef = 20E9518E634B49ABB71DCE40 /* CDVVibration.m */; };
|
||||
5E7AD5A8E68E484BA4751B09 /* CDVInAppBrowser.m in Sources */ = {isa = PBXBuildFile; fileRef = 3029EFFBE94840E08BFF1E33 /* CDVInAppBrowser.m */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -93,6 +94,8 @@
|
||||
5D9C1FE54F5040609267B2C0 /* CDVNotification.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; name = "CDVNotification.bundle"; path = "CDVNotification.bundle"; sourceTree = "<group>"; };
|
||||
20E9518E634B49ABB71DCE40 /* CDVVibration.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "CDVVibration.m"; path = "org.apache.cordova.vibration/CDVVibration.m"; sourceTree = "<group>"; fileEncoding = 4; };
|
||||
F3801EA4411E4664A8EC53CF /* CDVVibration.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "CDVVibration.h"; path = "org.apache.cordova.vibration/CDVVibration.h"; sourceTree = "<group>"; fileEncoding = 4; };
|
||||
3029EFFBE94840E08BFF1E33 /* CDVInAppBrowser.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "CDVInAppBrowser.m"; path = "org.apache.cordova.inappbrowser/CDVInAppBrowser.m"; sourceTree = "<group>"; fileEncoding = 4; };
|
||||
BA1E591F7B4746239462E69D /* CDVInAppBrowser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "CDVInAppBrowser.h"; path = "org.apache.cordova.inappbrowser/CDVInAppBrowser.h"; sourceTree = "<group>"; fileEncoding = 4; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -236,6 +239,8 @@
|
||||
B4B66470AFF74BF2A8571EE1 /* CDVNotification.h */,
|
||||
20E9518E634B49ABB71DCE40 /* CDVVibration.m */,
|
||||
F3801EA4411E4664A8EC53CF /* CDVVibration.h */,
|
||||
3029EFFBE94840E08BFF1E33 /* CDVInAppBrowser.m */,
|
||||
BA1E591F7B4746239462E69D /* CDVInAppBrowser.h */,
|
||||
);
|
||||
name = Plugins;
|
||||
path = Libr/Plugins;
|
||||
@@ -389,6 +394,7 @@
|
||||
80E040B65D8840F1AC5D77E9 /* CDVLocation.m in Sources */,
|
||||
0F97F9F0F6884BEE9E6014E2 /* CDVNotification.m in Sources */,
|
||||
46F5C9534FF04371A003E27C /* CDVVibration.m in Sources */,
|
||||
5E7AD5A8E68E484BA4751B09 /* CDVInAppBrowser.m in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
#import <Cordova/CDVPlugin.h>
|
||||
#import <Cordova/CDVInvokedUrlCommand.h>
|
||||
#import <Cordova/CDVScreenOrientationDelegate.h>
|
||||
#import <Cordova/CDVWebViewDelegate.h>
|
||||
|
||||
@class CDVInAppBrowserViewController;
|
||||
|
||||
@interface CDVInAppBrowser : CDVPlugin {
|
||||
BOOL _injectedIframeBridge;
|
||||
}
|
||||
|
||||
@property (nonatomic, retain) CDVInAppBrowserViewController* inAppBrowserViewController;
|
||||
@property (nonatomic, copy) NSString* callbackId;
|
||||
|
||||
- (void)open:(CDVInvokedUrlCommand*)command;
|
||||
- (void)close:(CDVInvokedUrlCommand*)command;
|
||||
- (void)injectScriptCode:(CDVInvokedUrlCommand*)command;
|
||||
- (void)show:(CDVInvokedUrlCommand*)command;
|
||||
|
||||
@end
|
||||
|
||||
@interface CDVInAppBrowserOptions : NSObject {}
|
||||
|
||||
@property (nonatomic, assign) BOOL location;
|
||||
@property (nonatomic, assign) BOOL toolbar;
|
||||
@property (nonatomic, copy) NSString* closebuttoncaption;
|
||||
@property (nonatomic, copy) NSString* toolbarposition;
|
||||
|
||||
@property (nonatomic, copy) NSString* presentationstyle;
|
||||
@property (nonatomic, copy) NSString* transitionstyle;
|
||||
|
||||
@property (nonatomic, assign) BOOL enableviewportscale;
|
||||
@property (nonatomic, assign) BOOL mediaplaybackrequiresuseraction;
|
||||
@property (nonatomic, assign) BOOL allowinlinemediaplayback;
|
||||
@property (nonatomic, assign) BOOL keyboarddisplayrequiresuseraction;
|
||||
@property (nonatomic, assign) BOOL suppressesincrementalrendering;
|
||||
@property (nonatomic, assign) BOOL hidden;
|
||||
@property (nonatomic, assign) BOOL disallowoverscroll;
|
||||
|
||||
+ (CDVInAppBrowserOptions*)parseOptions:(NSString*)options;
|
||||
|
||||
@end
|
||||
|
||||
@interface CDVInAppBrowserViewController : UIViewController <UIWebViewDelegate>{
|
||||
@private
|
||||
NSString* _userAgent;
|
||||
NSString* _prevUserAgent;
|
||||
NSInteger _userAgentLockToken;
|
||||
CDVInAppBrowserOptions *_browserOptions;
|
||||
CDVWebViewDelegate* _webViewDelegate;
|
||||
}
|
||||
|
||||
@property (nonatomic, strong) IBOutlet UIWebView* webView;
|
||||
@property (nonatomic, strong) IBOutlet UIBarButtonItem* closeButton;
|
||||
@property (nonatomic, strong) IBOutlet UILabel* addressLabel;
|
||||
@property (nonatomic, strong) IBOutlet UIBarButtonItem* backButton;
|
||||
@property (nonatomic, strong) IBOutlet UIBarButtonItem* forwardButton;
|
||||
@property (nonatomic, strong) IBOutlet UIActivityIndicatorView* spinner;
|
||||
@property (nonatomic, strong) IBOutlet UIToolbar* toolbar;
|
||||
|
||||
@property (nonatomic, weak) id <CDVScreenOrientationDelegate> orientationDelegate;
|
||||
@property (nonatomic, weak) CDVInAppBrowser* navigationDelegate;
|
||||
@property (nonatomic) NSURL* currentURL;
|
||||
|
||||
- (void)close;
|
||||
- (void)navigateTo:(NSURL*)url;
|
||||
- (void)showLocationBar:(BOOL)show;
|
||||
- (void)showToolBar:(BOOL)show : (NSString *) toolbarPosition;
|
||||
- (void)setCloseButtonTitle:(NSString*)title;
|
||||
|
||||
- (id)initWithUserAgent:(NSString*)userAgent prevUserAgent:(NSString*)prevUserAgent browserOptions: (CDVInAppBrowserOptions*) browserOptions;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,920 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
#import "CDVInAppBrowser.h"
|
||||
#import <Cordova/CDVPluginResult.h>
|
||||
#import <Cordova/CDVUserAgentUtil.h>
|
||||
#import <Cordova/CDVJSON.h>
|
||||
|
||||
#define kInAppBrowserTargetSelf @"_self"
|
||||
#define kInAppBrowserTargetSystem @"_system"
|
||||
#define kInAppBrowserTargetBlank @"_blank"
|
||||
|
||||
#define kInAppBrowserToolbarBarPositionBottom @"bottom"
|
||||
#define kInAppBrowserToolbarBarPositionTop @"top"
|
||||
|
||||
#define TOOLBAR_HEIGHT 44.0
|
||||
#define LOCATIONBAR_HEIGHT 21.0
|
||||
#define FOOTER_HEIGHT ((TOOLBAR_HEIGHT) + (LOCATIONBAR_HEIGHT))
|
||||
|
||||
#pragma mark CDVInAppBrowser
|
||||
|
||||
@interface CDVInAppBrowser () {
|
||||
NSInteger _previousStatusBarStyle;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation CDVInAppBrowser
|
||||
|
||||
- (CDVInAppBrowser*)initWithWebView:(UIWebView*)theWebView
|
||||
{
|
||||
self = [super initWithWebView:theWebView];
|
||||
if (self != nil) {
|
||||
_previousStatusBarStyle = -1;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)onReset
|
||||
{
|
||||
[self close:nil];
|
||||
}
|
||||
|
||||
- (void)close:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
if (self.inAppBrowserViewController == nil) {
|
||||
NSLog(@"IAB.close() called but it was already closed.");
|
||||
return;
|
||||
}
|
||||
// Things are cleaned up in browserExit.
|
||||
[self.inAppBrowserViewController close];
|
||||
}
|
||||
|
||||
- (BOOL) isSystemUrl:(NSURL*)url
|
||||
{
|
||||
if ([[url host] isEqualToString:@"itunes.apple.com"]) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)open:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
CDVPluginResult* pluginResult;
|
||||
|
||||
NSString* url = [command argumentAtIndex:0];
|
||||
NSString* target = [command argumentAtIndex:1 withDefault:kInAppBrowserTargetSelf];
|
||||
NSString* options = [command argumentAtIndex:2 withDefault:@"" andClass:[NSString class]];
|
||||
|
||||
self.callbackId = command.callbackId;
|
||||
|
||||
if (url != nil) {
|
||||
NSURL* baseUrl = [self.webView.request URL];
|
||||
NSURL* absoluteUrl = [[NSURL URLWithString:url relativeToURL:baseUrl] absoluteURL];
|
||||
|
||||
if ([self isSystemUrl:absoluteUrl]) {
|
||||
target = kInAppBrowserTargetSystem;
|
||||
}
|
||||
|
||||
if ([target isEqualToString:kInAppBrowserTargetSelf]) {
|
||||
[self openInCordovaWebView:absoluteUrl withOptions:options];
|
||||
} else if ([target isEqualToString:kInAppBrowserTargetSystem]) {
|
||||
[self openInSystem:absoluteUrl];
|
||||
} else { // _blank or anything else
|
||||
[self openInInAppBrowser:absoluteUrl withOptions:options];
|
||||
}
|
||||
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
|
||||
} else {
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"incorrect number of arguments"];
|
||||
}
|
||||
|
||||
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
|
||||
}
|
||||
|
||||
- (void)openInInAppBrowser:(NSURL*)url withOptions:(NSString*)options
|
||||
{
|
||||
CDVInAppBrowserOptions* browserOptions = [CDVInAppBrowserOptions parseOptions:options];
|
||||
if (self.inAppBrowserViewController == nil) {
|
||||
NSString* originalUA = [CDVUserAgentUtil originalUserAgent];
|
||||
self.inAppBrowserViewController = [[CDVInAppBrowserViewController alloc] initWithUserAgent:originalUA prevUserAgent:[self.commandDelegate userAgent] browserOptions: browserOptions];
|
||||
self.inAppBrowserViewController.navigationDelegate = self;
|
||||
|
||||
if ([self.viewController conformsToProtocol:@protocol(CDVScreenOrientationDelegate)]) {
|
||||
self.inAppBrowserViewController.orientationDelegate = (UIViewController <CDVScreenOrientationDelegate>*)self.viewController;
|
||||
}
|
||||
}
|
||||
|
||||
[self.inAppBrowserViewController showLocationBar:browserOptions.location];
|
||||
[self.inAppBrowserViewController showToolBar:browserOptions.toolbar :browserOptions.toolbarposition];
|
||||
if (browserOptions.closebuttoncaption != nil) {
|
||||
[self.inAppBrowserViewController setCloseButtonTitle:browserOptions.closebuttoncaption];
|
||||
}
|
||||
// Set Presentation Style
|
||||
UIModalPresentationStyle presentationStyle = UIModalPresentationFullScreen; // default
|
||||
if (browserOptions.presentationstyle != nil) {
|
||||
if ([[browserOptions.presentationstyle lowercaseString] isEqualToString:@"pagesheet"]) {
|
||||
presentationStyle = UIModalPresentationPageSheet;
|
||||
} else if ([[browserOptions.presentationstyle lowercaseString] isEqualToString:@"formsheet"]) {
|
||||
presentationStyle = UIModalPresentationFormSheet;
|
||||
}
|
||||
}
|
||||
self.inAppBrowserViewController.modalPresentationStyle = presentationStyle;
|
||||
|
||||
// Set Transition Style
|
||||
UIModalTransitionStyle transitionStyle = UIModalTransitionStyleCoverVertical; // default
|
||||
if (browserOptions.transitionstyle != nil) {
|
||||
if ([[browserOptions.transitionstyle lowercaseString] isEqualToString:@"fliphorizontal"]) {
|
||||
transitionStyle = UIModalTransitionStyleFlipHorizontal;
|
||||
} else if ([[browserOptions.transitionstyle lowercaseString] isEqualToString:@"crossdissolve"]) {
|
||||
transitionStyle = UIModalTransitionStyleCrossDissolve;
|
||||
}
|
||||
}
|
||||
self.inAppBrowserViewController.modalTransitionStyle = transitionStyle;
|
||||
|
||||
// prevent webView from bouncing
|
||||
if (browserOptions.disallowoverscroll) {
|
||||
if ([self.inAppBrowserViewController.webView respondsToSelector:@selector(scrollView)]) {
|
||||
((UIScrollView*)[self.inAppBrowserViewController.webView scrollView]).bounces = NO;
|
||||
} else {
|
||||
for (id subview in self.inAppBrowserViewController.webView.subviews) {
|
||||
if ([[subview class] isSubclassOfClass:[UIScrollView class]]) {
|
||||
((UIScrollView*)subview).bounces = NO;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UIWebView options
|
||||
self.inAppBrowserViewController.webView.scalesPageToFit = browserOptions.enableviewportscale;
|
||||
self.inAppBrowserViewController.webView.mediaPlaybackRequiresUserAction = browserOptions.mediaplaybackrequiresuseraction;
|
||||
self.inAppBrowserViewController.webView.allowsInlineMediaPlayback = browserOptions.allowinlinemediaplayback;
|
||||
if (IsAtLeastiOSVersion(@"6.0")) {
|
||||
self.inAppBrowserViewController.webView.keyboardDisplayRequiresUserAction = browserOptions.keyboarddisplayrequiresuseraction;
|
||||
self.inAppBrowserViewController.webView.suppressesIncrementalRendering = browserOptions.suppressesincrementalrendering;
|
||||
}
|
||||
|
||||
[self.inAppBrowserViewController navigateTo:url];
|
||||
if (!browserOptions.hidden) {
|
||||
[self show:nil];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)show:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
if (self.inAppBrowserViewController == nil) {
|
||||
NSLog(@"Tried to show IAB after it was closed.");
|
||||
return;
|
||||
}
|
||||
if (_previousStatusBarStyle != -1) {
|
||||
NSLog(@"Tried to show IAB while already shown");
|
||||
return;
|
||||
}
|
||||
|
||||
_previousStatusBarStyle = [UIApplication sharedApplication].statusBarStyle;
|
||||
|
||||
UINavigationController* nav = [[UINavigationController alloc]
|
||||
initWithRootViewController:self.inAppBrowserViewController];
|
||||
nav.navigationBarHidden = YES;
|
||||
// Run later to avoid the "took a long time" log message.
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (self.inAppBrowserViewController != nil) {
|
||||
[self.viewController presentModalViewController:nav animated:YES];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)openInCordovaWebView:(NSURL*)url withOptions:(NSString*)options
|
||||
{
|
||||
if ([self.commandDelegate URLIsWhitelisted:url]) {
|
||||
NSURLRequest* request = [NSURLRequest requestWithURL:url];
|
||||
[self.webView loadRequest:request];
|
||||
} else { // this assumes the InAppBrowser can be excepted from the white-list
|
||||
[self openInInAppBrowser:url withOptions:options];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)openInSystem:(NSURL*)url
|
||||
{
|
||||
if ([[UIApplication sharedApplication] canOpenURL:url]) {
|
||||
[[UIApplication sharedApplication] openURL:url];
|
||||
} else { // handle any custom schemes to plugins
|
||||
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
// '%@' marker).
|
||||
//
|
||||
// If no wrapper is supplied, then the source string is executed directly.
|
||||
|
||||
- (void)injectDeferredObject:(NSString*)source withWrapper:(NSString*)jsWrapper
|
||||
{
|
||||
if (!_injectedIframeBridge) {
|
||||
_injectedIframeBridge = YES;
|
||||
// Create an iframe bridge in the new document to communicate with the CDVInAppBrowserViewController
|
||||
[self.inAppBrowserViewController.webView stringByEvaluatingJavaScriptFromString:@"(function(d){var e = _cdvIframeBridge = d.createElement('iframe');e.style.display='none';d.body.appendChild(e);})(document)"];
|
||||
}
|
||||
|
||||
if (jsWrapper != nil) {
|
||||
NSString* sourceArrayString = [@[source] JSONString];
|
||||
if (sourceArrayString) {
|
||||
NSString* sourceString = [sourceArrayString substringWithRange:NSMakeRange(1, [sourceArrayString length] - 2)];
|
||||
NSString* jsToInject = [NSString stringWithFormat:jsWrapper, sourceString];
|
||||
[self.inAppBrowserViewController.webView stringByEvaluatingJavaScriptFromString:jsToInject];
|
||||
}
|
||||
} else {
|
||||
[self.inAppBrowserViewController.webView stringByEvaluatingJavaScriptFromString:source];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)injectScriptCode:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
NSString* jsWrapper = nil;
|
||||
|
||||
if ((command.callbackId != nil) && ![command.callbackId isEqualToString:@"INVALID"]) {
|
||||
jsWrapper = [NSString stringWithFormat:@"_cdvIframeBridge.src='gap-iab://%@/'+encodeURIComponent(JSON.stringify([eval(%%@)]));", command.callbackId];
|
||||
}
|
||||
[self injectDeferredObject:[command argumentAtIndex:0] withWrapper:jsWrapper];
|
||||
}
|
||||
|
||||
- (void)injectScriptFile:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
NSString* jsWrapper;
|
||||
|
||||
if ((command.callbackId != nil) && ![command.callbackId isEqualToString:@"INVALID"]) {
|
||||
jsWrapper = [NSString stringWithFormat:@"(function(d) { var c = d.createElement('script'); c.src = %%@; c.onload = function() { _cdvIframeBridge.src='gap-iab://%@'; }; d.body.appendChild(c); })(document)", command.callbackId];
|
||||
} else {
|
||||
jsWrapper = @"(function(d) { var c = d.createElement('script'); c.src = %@; d.body.appendChild(c); })(document)";
|
||||
}
|
||||
[self injectDeferredObject:[command argumentAtIndex:0] withWrapper:jsWrapper];
|
||||
}
|
||||
|
||||
- (void)injectStyleCode:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
NSString* jsWrapper;
|
||||
|
||||
if ((command.callbackId != nil) && ![command.callbackId isEqualToString:@"INVALID"]) {
|
||||
jsWrapper = [NSString stringWithFormat:@"(function(d) { var c = d.createElement('style'); c.innerHTML = %%@; c.onload = function() { _cdvIframeBridge.src='gap-iab://%@'; }; d.body.appendChild(c); })(document)", command.callbackId];
|
||||
} else {
|
||||
jsWrapper = @"(function(d) { var c = d.createElement('style'); c.innerHTML = %@; d.body.appendChild(c); })(document)";
|
||||
}
|
||||
[self injectDeferredObject:[command argumentAtIndex:0] withWrapper:jsWrapper];
|
||||
}
|
||||
|
||||
- (void)injectStyleFile:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
NSString* jsWrapper;
|
||||
|
||||
if ((command.callbackId != nil) && ![command.callbackId isEqualToString:@"INVALID"]) {
|
||||
jsWrapper = [NSString stringWithFormat:@"(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%@; c.onload = function() { _cdvIframeBridge.src='gap-iab://%@'; }; d.body.appendChild(c); })(document)", command.callbackId];
|
||||
} else {
|
||||
jsWrapper = @"(function(d) { var c = d.createElement('link'); c.rel='stylesheet', c.type='text/css'; c.href = %@; d.body.appendChild(c); })(document)";
|
||||
}
|
||||
[self injectDeferredObject:[command argumentAtIndex:0] withWrapper:jsWrapper];
|
||||
}
|
||||
|
||||
/**
|
||||
* The iframe bridge provided for the InAppBrowser is capable of executing any oustanding callback belonging
|
||||
* to the InAppBrowser plugin. Care has been taken that other callbacks cannot be triggered, and that no
|
||||
* other code execution is possible.
|
||||
*
|
||||
* To trigger the bridge, the iframe (or any other resource) should attempt to load a url of the form:
|
||||
*
|
||||
* gap-iab://<callbackId>/<arguments>
|
||||
*
|
||||
* where <callbackId> is the string id of the callback to trigger (something like "InAppBrowser0123456789")
|
||||
*
|
||||
* If present, the path component of the special gap-iab:// url is expected to be a URL-escaped JSON-encoded
|
||||
* value to pass to the callback. [NSURL path] should take care of the URL-unescaping, and a JSON_EXCEPTION
|
||||
* is returned if the JSON is invalid.
|
||||
*/
|
||||
- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
|
||||
{
|
||||
NSURL* url = request.URL;
|
||||
BOOL isTopLevelNavigation = [request.URL isEqual:[request mainDocumentURL]];
|
||||
|
||||
// See if the url uses the 'gap-iab' protocol. If so, the host should be the id of a callback to execute,
|
||||
// and the path, if present, should be a JSON-encoded value to pass to the callback.
|
||||
if ([[url scheme] isEqualToString:@"gap-iab"]) {
|
||||
NSString* scriptCallbackId = [url host];
|
||||
CDVPluginResult* pluginResult = nil;
|
||||
|
||||
if ([scriptCallbackId hasPrefix:@"InAppBrowser"]) {
|
||||
NSString* scriptResult = [url path];
|
||||
NSError* __autoreleasing error = nil;
|
||||
|
||||
// The message should be a JSON-encoded array of the result of the script which executed.
|
||||
if ((scriptResult != nil) && ([scriptResult length] > 1)) {
|
||||
scriptResult = [scriptResult substringFromIndex:1];
|
||||
NSData* decodedResult = [NSJSONSerialization JSONObjectWithData:[scriptResult dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
|
||||
if ((error == nil) && [decodedResult isKindOfClass:[NSArray class]]) {
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:(NSArray*)decodedResult];
|
||||
} else {
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_JSON_EXCEPTION];
|
||||
}
|
||||
} else {
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:@[]];
|
||||
}
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:scriptCallbackId];
|
||||
return NO;
|
||||
}
|
||||
} else if ((self.callbackId != nil) && isTopLevelNavigation) {
|
||||
// Send a loadstart event for each top-level navigation (includes redirects).
|
||||
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
|
||||
messageAsDictionary:@{@"type":@"loadstart", @"url":[url absoluteString]}];
|
||||
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
|
||||
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)webViewDidStartLoad:(UIWebView*)theWebView
|
||||
{
|
||||
_injectedIframeBridge = NO;
|
||||
}
|
||||
|
||||
- (void)webViewDidFinishLoad:(UIWebView*)theWebView
|
||||
{
|
||||
if (self.callbackId != nil) {
|
||||
// TODO: It would be more useful to return the URL the page is actually on (e.g. if it's been redirected).
|
||||
NSString* url = [self.inAppBrowserViewController.currentURL absoluteString];
|
||||
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
|
||||
messageAsDictionary:@{@"type":@"loadstop", @"url":url}];
|
||||
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
|
||||
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error
|
||||
{
|
||||
if (self.callbackId != nil) {
|
||||
NSString* url = [self.inAppBrowserViewController.currentURL absoluteString];
|
||||
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
|
||||
messageAsDictionary:@{@"type":@"loaderror", @"url":url, @"code": [NSNumber numberWithInt:error.code], @"message": error.localizedDescription}];
|
||||
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
|
||||
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)browserExit
|
||||
{
|
||||
if (self.callbackId != nil) {
|
||||
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
|
||||
messageAsDictionary:@{@"type":@"exit"}];
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
|
||||
self.callbackId = nil;
|
||||
}
|
||||
// Set navigationDelegate to nil to ensure no callbacks are received from it.
|
||||
self.inAppBrowserViewController.navigationDelegate = nil;
|
||||
// Don't recycle the ViewController since it may be consuming a lot of memory.
|
||||
// Also - this is required for the PDF/User-Agent bug work-around.
|
||||
self.inAppBrowserViewController = nil;
|
||||
|
||||
_previousStatusBarStyle = -1;
|
||||
|
||||
if (IsAtLeastiOSVersion(@"7.0")) {
|
||||
[[UIApplication sharedApplication] setStatusBarStyle:_previousStatusBarStyle];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark CDVInAppBrowserViewController
|
||||
|
||||
@implementation CDVInAppBrowserViewController
|
||||
|
||||
@synthesize currentURL;
|
||||
|
||||
- (id)initWithUserAgent:(NSString*)userAgent prevUserAgent:(NSString*)prevUserAgent browserOptions: (CDVInAppBrowserOptions*) browserOptions
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_userAgent = userAgent;
|
||||
_prevUserAgent = prevUserAgent;
|
||||
_browserOptions = browserOptions;
|
||||
_webViewDelegate = [[CDVWebViewDelegate alloc] initWithDelegate:self];
|
||||
[self createViews];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)createViews
|
||||
{
|
||||
// We create the views in code for primarily for ease of upgrades and not requiring an external .xib to be included
|
||||
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
BOOL toolbarIsAtBottom = ![_browserOptions.toolbarposition isEqualToString:kInAppBrowserToolbarBarPositionTop];
|
||||
webViewBounds.size.height -= _browserOptions.location ? FOOTER_HEIGHT : TOOLBAR_HEIGHT;
|
||||
self.webView = [[UIWebView alloc] initWithFrame:webViewBounds];
|
||||
|
||||
self.webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
|
||||
|
||||
[self.view addSubview:self.webView];
|
||||
[self.view sendSubviewToBack:self.webView];
|
||||
|
||||
self.webView.delegate = _webViewDelegate;
|
||||
self.webView.backgroundColor = [UIColor whiteColor];
|
||||
|
||||
self.webView.clearsContextBeforeDrawing = YES;
|
||||
self.webView.clipsToBounds = YES;
|
||||
self.webView.contentMode = UIViewContentModeScaleToFill;
|
||||
self.webView.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
|
||||
self.webView.multipleTouchEnabled = YES;
|
||||
self.webView.opaque = YES;
|
||||
self.webView.scalesPageToFit = NO;
|
||||
self.webView.userInteractionEnabled = YES;
|
||||
|
||||
self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
|
||||
self.spinner.alpha = 1.000;
|
||||
self.spinner.autoresizesSubviews = YES;
|
||||
self.spinner.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
|
||||
self.spinner.clearsContextBeforeDrawing = NO;
|
||||
self.spinner.clipsToBounds = NO;
|
||||
self.spinner.contentMode = UIViewContentModeScaleToFill;
|
||||
self.spinner.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
|
||||
self.spinner.frame = CGRectMake(454.0, 231.0, 20.0, 20.0);
|
||||
self.spinner.hidden = YES;
|
||||
self.spinner.hidesWhenStopped = YES;
|
||||
self.spinner.multipleTouchEnabled = NO;
|
||||
self.spinner.opaque = NO;
|
||||
self.spinner.userInteractionEnabled = NO;
|
||||
[self.spinner stopAnimating];
|
||||
|
||||
self.closeButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(close)];
|
||||
self.closeButton.enabled = YES;
|
||||
|
||||
UIBarButtonItem* flexibleSpaceButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
|
||||
|
||||
UIBarButtonItem* fixedSpaceButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
|
||||
fixedSpaceButton.width = 20;
|
||||
|
||||
float toolbarY = toolbarIsAtBottom ? self.view.bounds.size.height - TOOLBAR_HEIGHT : 0.0;
|
||||
CGRect toolbarFrame = CGRectMake(0.0, toolbarY, self.view.bounds.size.width, TOOLBAR_HEIGHT);
|
||||
|
||||
self.toolbar = [[UIToolbar alloc] initWithFrame:toolbarFrame];
|
||||
self.toolbar.alpha = 1.000;
|
||||
self.toolbar.autoresizesSubviews = YES;
|
||||
self.toolbar.autoresizingMask = toolbarIsAtBottom ? (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin) : UIViewAutoresizingFlexibleWidth;
|
||||
self.toolbar.barStyle = UIBarStyleBlackOpaque;
|
||||
self.toolbar.clearsContextBeforeDrawing = NO;
|
||||
self.toolbar.clipsToBounds = NO;
|
||||
self.toolbar.contentMode = UIViewContentModeScaleToFill;
|
||||
self.toolbar.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
|
||||
self.toolbar.hidden = NO;
|
||||
self.toolbar.multipleTouchEnabled = NO;
|
||||
self.toolbar.opaque = NO;
|
||||
self.toolbar.userInteractionEnabled = YES;
|
||||
|
||||
CGFloat labelInset = 5.0;
|
||||
float locationBarY = toolbarIsAtBottom ? self.view.bounds.size.height - FOOTER_HEIGHT : self.view.bounds.size.height - LOCATIONBAR_HEIGHT;
|
||||
|
||||
self.addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(labelInset, locationBarY, self.view.bounds.size.width - labelInset, LOCATIONBAR_HEIGHT)];
|
||||
self.addressLabel.adjustsFontSizeToFitWidth = NO;
|
||||
self.addressLabel.alpha = 1.000;
|
||||
self.addressLabel.autoresizesSubviews = YES;
|
||||
self.addressLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
|
||||
self.addressLabel.backgroundColor = [UIColor clearColor];
|
||||
self.addressLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
|
||||
self.addressLabel.clearsContextBeforeDrawing = YES;
|
||||
self.addressLabel.clipsToBounds = YES;
|
||||
self.addressLabel.contentMode = UIViewContentModeScaleToFill;
|
||||
self.addressLabel.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
|
||||
self.addressLabel.enabled = YES;
|
||||
self.addressLabel.hidden = NO;
|
||||
self.addressLabel.lineBreakMode = UILineBreakModeTailTruncation;
|
||||
self.addressLabel.minimumFontSize = 10.000;
|
||||
self.addressLabel.multipleTouchEnabled = NO;
|
||||
self.addressLabel.numberOfLines = 1;
|
||||
self.addressLabel.opaque = NO;
|
||||
self.addressLabel.shadowOffset = CGSizeMake(0.0, -1.0);
|
||||
self.addressLabel.text = NSLocalizedString(@"Loading...", nil);
|
||||
self.addressLabel.textAlignment = UITextAlignmentLeft;
|
||||
self.addressLabel.textColor = [UIColor colorWithWhite:1.000 alpha:1.000];
|
||||
self.addressLabel.userInteractionEnabled = NO;
|
||||
|
||||
NSString* frontArrowString = NSLocalizedString(@"►", nil); // create arrow from Unicode char
|
||||
self.forwardButton = [[UIBarButtonItem alloc] initWithTitle:frontArrowString style:UIBarButtonItemStylePlain target:self action:@selector(goForward:)];
|
||||
self.forwardButton.enabled = YES;
|
||||
self.forwardButton.imageInsets = UIEdgeInsetsZero;
|
||||
|
||||
NSString* backArrowString = NSLocalizedString(@"◄", nil); // create arrow from Unicode char
|
||||
self.backButton = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStylePlain target:self action:@selector(goBack:)];
|
||||
self.backButton.enabled = YES;
|
||||
self.backButton.imageInsets = UIEdgeInsetsZero;
|
||||
|
||||
[self.toolbar setItems:@[self.closeButton, flexibleSpaceButton, self.backButton, fixedSpaceButton, self.forwardButton]];
|
||||
|
||||
self.view.backgroundColor = [UIColor grayColor];
|
||||
[self.view addSubview:self.toolbar];
|
||||
[self.view addSubview:self.addressLabel];
|
||||
[self.view addSubview:self.spinner];
|
||||
}
|
||||
|
||||
- (void) setWebViewFrame : (CGRect) frame {
|
||||
NSLog(@"Setting the WebView's frame to %@", NSStringFromCGRect(frame));
|
||||
[self.webView setFrame:frame];
|
||||
}
|
||||
|
||||
- (void)setCloseButtonTitle:(NSString*)title
|
||||
{
|
||||
// the advantage of using UIBarButtonSystemItemDone is the system will localize it for you automatically
|
||||
// but, if you want to set this yourself, knock yourself out (we can't set the title for a system Done button, so we have to create a new one)
|
||||
self.closeButton = nil;
|
||||
self.closeButton = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStyleBordered target:self action:@selector(close)];
|
||||
self.closeButton.enabled = YES;
|
||||
self.closeButton.tintColor = [UIColor colorWithRed:60.0 / 255.0 green:136.0 / 255.0 blue:230.0 / 255.0 alpha:1];
|
||||
|
||||
NSMutableArray* items = [self.toolbar.items mutableCopy];
|
||||
[items replaceObjectAtIndex:0 withObject:self.closeButton];
|
||||
[self.toolbar setItems:items];
|
||||
}
|
||||
|
||||
- (void)showLocationBar:(BOOL)show
|
||||
{
|
||||
CGRect locationbarFrame = self.addressLabel.frame;
|
||||
|
||||
BOOL toolbarVisible = !self.toolbar.hidden;
|
||||
|
||||
// prevent double show/hide
|
||||
if (show == !(self.addressLabel.hidden)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (show) {
|
||||
self.addressLabel.hidden = NO;
|
||||
|
||||
if (toolbarVisible) {
|
||||
// toolBar at the bottom, leave as is
|
||||
// put locationBar on top of the toolBar
|
||||
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
webViewBounds.size.height -= FOOTER_HEIGHT;
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
|
||||
locationbarFrame.origin.y = webViewBounds.size.height;
|
||||
self.addressLabel.frame = locationbarFrame;
|
||||
} else {
|
||||
// no toolBar, so put locationBar at the bottom
|
||||
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
webViewBounds.size.height -= LOCATIONBAR_HEIGHT;
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
|
||||
locationbarFrame.origin.y = webViewBounds.size.height;
|
||||
self.addressLabel.frame = locationbarFrame;
|
||||
}
|
||||
} else {
|
||||
self.addressLabel.hidden = YES;
|
||||
|
||||
if (toolbarVisible) {
|
||||
// locationBar is on top of toolBar, hide locationBar
|
||||
|
||||
// webView take up whole height less toolBar height
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
webViewBounds.size.height -= TOOLBAR_HEIGHT;
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
} else {
|
||||
// no toolBar, expand webView to screen dimensions
|
||||
[self setWebViewFrame:self.view.bounds];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)showToolBar:(BOOL)show : (NSString *) toolbarPosition
|
||||
{
|
||||
CGRect toolbarFrame = self.toolbar.frame;
|
||||
CGRect locationbarFrame = self.addressLabel.frame;
|
||||
|
||||
BOOL locationbarVisible = !self.addressLabel.hidden;
|
||||
|
||||
// prevent double show/hide
|
||||
if (show == !(self.toolbar.hidden)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (show) {
|
||||
self.toolbar.hidden = NO;
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
|
||||
if (locationbarVisible) {
|
||||
// locationBar at the bottom, move locationBar up
|
||||
// put toolBar at the bottom
|
||||
webViewBounds.size.height -= FOOTER_HEIGHT;
|
||||
locationbarFrame.origin.y = webViewBounds.size.height;
|
||||
self.addressLabel.frame = locationbarFrame;
|
||||
self.toolbar.frame = toolbarFrame;
|
||||
} else {
|
||||
// no locationBar, so put toolBar at the bottom
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
webViewBounds.size.height -= TOOLBAR_HEIGHT;
|
||||
self.toolbar.frame = toolbarFrame;
|
||||
}
|
||||
|
||||
if ([toolbarPosition isEqualToString:kInAppBrowserToolbarBarPositionTop]) {
|
||||
toolbarFrame.origin.y = 0;
|
||||
webViewBounds.origin.y += toolbarFrame.size.height;
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
} else {
|
||||
toolbarFrame.origin.y = (webViewBounds.size.height + LOCATIONBAR_HEIGHT);
|
||||
}
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
|
||||
} else {
|
||||
self.toolbar.hidden = YES;
|
||||
|
||||
if (locationbarVisible) {
|
||||
// locationBar is on top of toolBar, hide toolBar
|
||||
// put locationBar at the bottom
|
||||
|
||||
// webView take up whole height less locationBar height
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
webViewBounds.size.height -= LOCATIONBAR_HEIGHT;
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
|
||||
// move locationBar down
|
||||
locationbarFrame.origin.y = webViewBounds.size.height;
|
||||
self.addressLabel.frame = locationbarFrame;
|
||||
} else {
|
||||
// no locationBar, expand webView to screen dimensions
|
||||
[self setWebViewFrame:self.view.bounds];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)viewDidLoad
|
||||
{
|
||||
[super viewDidLoad];
|
||||
}
|
||||
|
||||
- (void)viewDidUnload
|
||||
{
|
||||
[self.webView loadHTMLString:nil baseURL:nil];
|
||||
[CDVUserAgentUtil releaseLock:&_userAgentLockToken];
|
||||
[super viewDidUnload];
|
||||
}
|
||||
|
||||
- (UIStatusBarStyle)preferredStatusBarStyle
|
||||
{
|
||||
return UIStatusBarStyleDefault;
|
||||
}
|
||||
|
||||
- (void)close
|
||||
{
|
||||
[CDVUserAgentUtil releaseLock:&_userAgentLockToken];
|
||||
self.currentURL = nil;
|
||||
|
||||
if ((self.navigationDelegate != nil) && [self.navigationDelegate respondsToSelector:@selector(browserExit)]) {
|
||||
[self.navigationDelegate browserExit];
|
||||
}
|
||||
|
||||
// Run later to avoid the "took a long time" log message.
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if ([self respondsToSelector:@selector(presentingViewController)]) {
|
||||
[[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
|
||||
} else {
|
||||
[[self parentViewController] dismissModalViewControllerAnimated:YES];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)navigateTo:(NSURL*)url
|
||||
{
|
||||
NSURLRequest* request = [NSURLRequest requestWithURL:url];
|
||||
|
||||
if (_userAgentLockToken != 0) {
|
||||
[self.webView loadRequest:request];
|
||||
} else {
|
||||
[CDVUserAgentUtil acquireLock:^(NSInteger lockToken) {
|
||||
_userAgentLockToken = lockToken;
|
||||
[CDVUserAgentUtil setUserAgent:_userAgent lockToken:lockToken];
|
||||
[self.webView loadRequest:request];
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)goBack:(id)sender
|
||||
{
|
||||
[self.webView goBack];
|
||||
}
|
||||
|
||||
- (void)goForward:(id)sender
|
||||
{
|
||||
[self.webView goForward];
|
||||
}
|
||||
|
||||
- (void)viewWillAppear:(BOOL)animated
|
||||
{
|
||||
if (IsAtLeastiOSVersion(@"7.0")) {
|
||||
[[UIApplication sharedApplication] setStatusBarStyle:[self preferredStatusBarStyle]];
|
||||
}
|
||||
[self rePositionViews];
|
||||
|
||||
[super viewWillAppear:animated];
|
||||
}
|
||||
|
||||
//
|
||||
// On iOS 7 the status bar is part of the view's dimensions, therefore it's height has to be taken into account.
|
||||
// The height of it could be hardcoded as 20 pixels, but that would assume that the upcoming releases of iOS won't
|
||||
// change that value.
|
||||
//
|
||||
- (float) getStatusBarOffset {
|
||||
CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
|
||||
float statusBarOffset = IsAtLeastiOSVersion(@"7.0") ? MIN(statusBarFrame.size.width, statusBarFrame.size.height) : 0.0;
|
||||
return statusBarOffset;
|
||||
}
|
||||
|
||||
- (void) rePositionViews {
|
||||
if ([_browserOptions.toolbarposition isEqualToString:kInAppBrowserToolbarBarPositionTop]) {
|
||||
[self.webView setFrame:CGRectMake(self.webView.frame.origin.x, TOOLBAR_HEIGHT, self.webView.frame.size.width, self.webView.frame.size.height)];
|
||||
[self.toolbar setFrame:CGRectMake(self.toolbar.frame.origin.x, [self getStatusBarOffset], self.toolbar.frame.size.width, self.toolbar.frame.size.height)];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark UIWebViewDelegate
|
||||
|
||||
- (void)webViewDidStartLoad:(UIWebView*)theWebView
|
||||
{
|
||||
// loading url, start spinner, update back/forward
|
||||
|
||||
self.addressLabel.text = NSLocalizedString(@"Loading...", nil);
|
||||
self.backButton.enabled = theWebView.canGoBack;
|
||||
self.forwardButton.enabled = theWebView.canGoForward;
|
||||
|
||||
[self.spinner startAnimating];
|
||||
|
||||
return [self.navigationDelegate webViewDidStartLoad:theWebView];
|
||||
}
|
||||
|
||||
- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
|
||||
{
|
||||
BOOL isTopLevelNavigation = [request.URL isEqual:[request mainDocumentURL]];
|
||||
|
||||
if (isTopLevelNavigation) {
|
||||
self.currentURL = request.URL;
|
||||
}
|
||||
return [self.navigationDelegate webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
|
||||
}
|
||||
|
||||
- (void)webViewDidFinishLoad:(UIWebView*)theWebView
|
||||
{
|
||||
// update url, stop spinner, update back/forward
|
||||
|
||||
self.addressLabel.text = [self.currentURL absoluteString];
|
||||
self.backButton.enabled = theWebView.canGoBack;
|
||||
self.forwardButton.enabled = theWebView.canGoForward;
|
||||
|
||||
[self.spinner stopAnimating];
|
||||
|
||||
// Work around a bug where the first time a PDF is opened, all UIWebViews
|
||||
// reload their User-Agent from NSUserDefaults.
|
||||
// This work-around makes the following assumptions:
|
||||
// 1. The app has only a single Cordova Webview. If not, then the app should
|
||||
// take it upon themselves to load a PDF in the background as a part of
|
||||
// their start-up flow.
|
||||
// 2. That the PDF does not require any additional network requests. We change
|
||||
// the user-agent here back to that of the CDVViewController, so requests
|
||||
// from it must pass through its white-list. This *does* break PDFs that
|
||||
// contain links to other remote PDF/websites.
|
||||
// More info at https://issues.apache.org/jira/browse/CB-2225
|
||||
BOOL isPDF = [@"true" isEqualToString :[theWebView stringByEvaluatingJavaScriptFromString:@"document.body==null"]];
|
||||
if (isPDF) {
|
||||
[CDVUserAgentUtil setUserAgent:_prevUserAgent lockToken:_userAgentLockToken];
|
||||
}
|
||||
|
||||
[self.navigationDelegate webViewDidFinishLoad:theWebView];
|
||||
}
|
||||
|
||||
- (void)webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error
|
||||
{
|
||||
// log fail message, stop spinner, update back/forward
|
||||
NSLog(@"webView:didFailLoadWithError - %i: %@", error.code, [error localizedDescription]);
|
||||
|
||||
self.backButton.enabled = theWebView.canGoBack;
|
||||
self.forwardButton.enabled = theWebView.canGoForward;
|
||||
[self.spinner stopAnimating];
|
||||
|
||||
self.addressLabel.text = NSLocalizedString(@"Load Error", nil);
|
||||
|
||||
[self.navigationDelegate webView:theWebView didFailLoadWithError:error];
|
||||
}
|
||||
|
||||
#pragma mark CDVScreenOrientationDelegate
|
||||
|
||||
- (BOOL)shouldAutorotate
|
||||
{
|
||||
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(shouldAutorotate)]) {
|
||||
return [self.orientationDelegate shouldAutorotate];
|
||||
}
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (NSUInteger)supportedInterfaceOrientations
|
||||
{
|
||||
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(supportedInterfaceOrientations)]) {
|
||||
return [self.orientationDelegate supportedInterfaceOrientations];
|
||||
}
|
||||
|
||||
return 1 << UIInterfaceOrientationPortrait;
|
||||
}
|
||||
|
||||
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
|
||||
{
|
||||
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(shouldAutorotateToInterfaceOrientation:)]) {
|
||||
return [self.orientationDelegate shouldAutorotateToInterfaceOrientation:interfaceOrientation];
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CDVInAppBrowserOptions
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init]) {
|
||||
// default values
|
||||
self.location = YES;
|
||||
self.toolbar = YES;
|
||||
self.closebuttoncaption = nil;
|
||||
self.toolbarposition = kInAppBrowserToolbarBarPositionBottom;
|
||||
|
||||
self.enableviewportscale = NO;
|
||||
self.mediaplaybackrequiresuseraction = NO;
|
||||
self.allowinlinemediaplayback = NO;
|
||||
self.keyboarddisplayrequiresuseraction = YES;
|
||||
self.suppressesincrementalrendering = NO;
|
||||
self.hidden = NO;
|
||||
self.disallowoverscroll = NO;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (CDVInAppBrowserOptions*)parseOptions:(NSString*)options
|
||||
{
|
||||
CDVInAppBrowserOptions* obj = [[CDVInAppBrowserOptions alloc] init];
|
||||
|
||||
// NOTE: this parsing does not handle quotes within values
|
||||
NSArray* pairs = [options componentsSeparatedByString:@","];
|
||||
|
||||
// parse keys and values, set the properties
|
||||
for (NSString* pair in pairs) {
|
||||
NSArray* keyvalue = [pair componentsSeparatedByString:@"="];
|
||||
|
||||
if ([keyvalue count] == 2) {
|
||||
NSString* key = [[keyvalue objectAtIndex:0] lowercaseString];
|
||||
NSString* value = [keyvalue objectAtIndex:1];
|
||||
NSString* value_lc = [value lowercaseString];
|
||||
|
||||
BOOL isBoolean = [value_lc isEqualToString:@"yes"] || [value_lc isEqualToString:@"no"];
|
||||
NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
|
||||
[numberFormatter setAllowsFloats:YES];
|
||||
BOOL isNumber = [numberFormatter numberFromString:value_lc] != nil;
|
||||
|
||||
// set the property according to the key name
|
||||
if ([obj respondsToSelector:NSSelectorFromString(key)]) {
|
||||
if (isNumber) {
|
||||
[obj setValue:[numberFormatter numberFromString:value_lc] forKey:key];
|
||||
} else if (isBoolean) {
|
||||
[obj setValue:[NSNumber numberWithBool:[value_lc isEqualToString:@"yes"]] forKey:key];
|
||||
} else {
|
||||
[obj setValue:value forKey:key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -25,6 +25,9 @@
|
||||
<feature name="Notification">
|
||||
<param name="ios-package" value="CDVNotification" />
|
||||
</feature>
|
||||
<feature name="InAppBrowser">
|
||||
<param name="ios-package" value="CDVInAppBrowser" />
|
||||
</feature>
|
||||
<feature name="Vibration">
|
||||
<param name="ios-package" value="CDVVibration" />
|
||||
</feature>
|
||||
|
||||
@@ -55,6 +55,13 @@ module.exports = [
|
||||
"merges": [
|
||||
"navigator.notification"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "plugins/org.apache.cordova.inappbrowser/www/InAppBrowser.js",
|
||||
"id": "org.apache.cordova.inappbrowser.InAppBrowser",
|
||||
"clobbers": [
|
||||
"window.open"
|
||||
]
|
||||
}
|
||||
];
|
||||
module.exports.metadata =
|
||||
@@ -64,7 +71,8 @@ module.exports.metadata =
|
||||
"org.apache.cordova.device": "0.2.7",
|
||||
"org.apache.cordova.geolocation": "0.3.5",
|
||||
"org.apache.cordova.dialogs": "0.2.6",
|
||||
"org.apache.cordova.vibration": "0.3.7"
|
||||
"org.apache.cordova.vibration": "0.3.7",
|
||||
"org.apache.cordova.inappbrowser": "0.3.1"
|
||||
}
|
||||
// BOTTOM OF METADATA
|
||||
});
|
||||
@@ -6,17 +6,22 @@ class HomeController
|
||||
constructor: (@$scope, @$location, BookService, ScanService, @$ionicLoading, @$ionicActionSheet, @RecommendService)->
|
||||
if isUserLogedIn()
|
||||
showLoading(@$scope, @$ionicLoading)
|
||||
BookService.getBooks().success (result)=>
|
||||
@$scope.books = result.books
|
||||
@$scope.enableBackButton = false
|
||||
@$scope.rightButtons = [
|
||||
{
|
||||
type: 'button icon ion-shuffle'
|
||||
tap: (e) =>
|
||||
@showRecommendActionSheet()
|
||||
}
|
||||
]
|
||||
@$scope.loading.hide();
|
||||
@$scope.title = 'Libr - 你可能喜欢的书'
|
||||
@$scope.enableBackButton = false
|
||||
@$scope.rightButtons = [
|
||||
{
|
||||
type: 'button icon ion-shuffle'
|
||||
tap: (e) =>
|
||||
@showRecommendActionSheet()
|
||||
}
|
||||
]
|
||||
@RecommendService.popularBooksForMe (result)=>
|
||||
if result.length is 0
|
||||
alert '请先添加一些你阅读的书,再来查看推荐吧'
|
||||
return
|
||||
else
|
||||
@$scope.books = result
|
||||
@$scope.loading.hide();
|
||||
else
|
||||
@$location.path '/tab/settings'
|
||||
return
|
||||
@@ -42,11 +47,19 @@ class HomeController
|
||||
cancelText: '取消'
|
||||
cancel: ()->
|
||||
console.log('CANCELLED')
|
||||
buttonClicked: (index)->
|
||||
console.log('BUTTON CLICKED', index)
|
||||
buttonClicked: (index)=>
|
||||
console.log "#{index} has been taped"
|
||||
@changeRecommend index
|
||||
true
|
||||
destructiveButtonClicked: ()->
|
||||
console.log('DESTRUCT')
|
||||
true
|
||||
}
|
||||
changeRecommend: (index)=>
|
||||
@RecommendService.changeRecommendAction index, (result)=>
|
||||
if result.length is 0
|
||||
alert '喔,看来附近还没有好书推荐,快去推荐你的朋友也来使用吧!'
|
||||
else
|
||||
@$scope.books = result
|
||||
listArray = JSON.parse(localStorage.getItem 'recommend_action_sheet_full_arr')
|
||||
@$scope.title = 'Libr-' + listArray[index].text
|
||||
libr.controller 'HomeCtrl', HomeController
|
||||
@@ -16,22 +16,30 @@
|
||||
this.$ionicLoading = $ionicLoading;
|
||||
this.$ionicActionSheet = $ionicActionSheet;
|
||||
this.RecommendService = RecommendService;
|
||||
this.changeRecommend = __bind(this.changeRecommend, this);
|
||||
this.showRecommendActionSheet = __bind(this.showRecommendActionSheet, this);
|
||||
if (isUserLogedIn()) {
|
||||
showLoading(this.$scope, this.$ionicLoading);
|
||||
BookService.getBooks().success((function(_this) {
|
||||
this.$scope.title = 'Libr - 你可能喜欢的书';
|
||||
this.$scope.enableBackButton = false;
|
||||
this.$scope.rightButtons = [
|
||||
{
|
||||
type: 'button icon ion-shuffle',
|
||||
tap: (function(_this) {
|
||||
return function(e) {
|
||||
return _this.showRecommendActionSheet();
|
||||
};
|
||||
})(this)
|
||||
}
|
||||
];
|
||||
this.RecommendService.popularBooksForMe((function(_this) {
|
||||
return function(result) {
|
||||
_this.$scope.books = result.books;
|
||||
_this.$scope.enableBackButton = false;
|
||||
_this.$scope.rightButtons = [
|
||||
{
|
||||
type: 'button icon ion-shuffle',
|
||||
tap: function(e) {
|
||||
return _this.showRecommendActionSheet();
|
||||
}
|
||||
}
|
||||
];
|
||||
return _this.$scope.loading.hide();
|
||||
if (result.length === 0) {
|
||||
alert('请先添加一些你阅读的书,再来查看推荐吧');
|
||||
} else {
|
||||
_this.$scope.books = result;
|
||||
return _this.$scope.loading.hide();
|
||||
}
|
||||
};
|
||||
})(this));
|
||||
} else {
|
||||
@@ -67,17 +75,34 @@
|
||||
cancel: function() {
|
||||
return console.log('CANCELLED');
|
||||
},
|
||||
buttonClicked: function(index) {
|
||||
console.log('BUTTON CLICKED', index);
|
||||
return true;
|
||||
},
|
||||
buttonClicked: (function(_this) {
|
||||
return function(index) {
|
||||
console.log("" + index + " has been taped");
|
||||
_this.changeRecommend(index);
|
||||
return true;
|
||||
};
|
||||
})(this),
|
||||
destructiveButtonClicked: function() {
|
||||
console.log('DESTRUCT');
|
||||
return true;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
HomeController.prototype.changeRecommend = function(index) {
|
||||
return this.RecommendService.changeRecommendAction(index, (function(_this) {
|
||||
return function(result) {
|
||||
var listArray;
|
||||
if (result.length === 0) {
|
||||
return alert('喔,看来附近还没有好书推荐,快去推荐你的朋友也来使用吧!');
|
||||
} else {
|
||||
_this.$scope.books = result;
|
||||
listArray = JSON.parse(localStorage.getItem('recommend_action_sheet_full_arr'));
|
||||
return _this.$scope.title = 'Libr-' + listArray[index].text;
|
||||
}
|
||||
};
|
||||
})(this));
|
||||
};
|
||||
|
||||
return HomeController;
|
||||
|
||||
})();
|
||||
|
||||
@@ -6,6 +6,7 @@ class SettingsController
|
||||
constructor: (@$scope, @$ionicModal, @AuthService, @$state) ->
|
||||
@$scope.login = @login
|
||||
@$scope.logout = @logout
|
||||
@$scope.feedback = @feedback
|
||||
if isUserLogedIn() then @$scope.isLogedIn = true else @$scope.isLogedIn = false
|
||||
|
||||
|
||||
@@ -21,6 +22,9 @@ class SettingsController
|
||||
localStorage.removeItem 'token'
|
||||
@$state.go 'login'
|
||||
|
||||
feedback: ->
|
||||
window.open('https://jinshuju.net/f/F96z3s', '_blank', 'location=no')
|
||||
|
||||
isUserLogedIn = ()->
|
||||
if localStorage.getItem('token') isnt null and localStorage.getItem('email') isnt null
|
||||
true
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
this.login = __bind(this.login, this);
|
||||
this.$scope.login = this.login;
|
||||
this.$scope.logout = this.logout;
|
||||
this.$scope.feedback = this.feedback;
|
||||
if (isUserLogedIn()) {
|
||||
this.$scope.isLogedIn = true;
|
||||
} else {
|
||||
@@ -42,6 +43,10 @@
|
||||
return this.$state.go('login');
|
||||
};
|
||||
|
||||
SettingsController.prototype.feedback = function() {
|
||||
return window.open('https://jinshuju.net/f/F96z3s', '_blank', 'location=no');
|
||||
};
|
||||
|
||||
isUserLogedIn = function() {
|
||||
if (localStorage.getItem('token') !== null && localStorage.getItem('email') !== null) {
|
||||
return true;
|
||||
|
||||
@@ -1,18 +1,60 @@
|
||||
libr = angular.module 'libr.services.recommend', []
|
||||
|
||||
class RecommendService
|
||||
baseUrl = 'http://libr.herokuapp.com/api/v1'
|
||||
email = localStorage.getItem 'email'
|
||||
token = localStorage.getItem 'token'
|
||||
|
||||
@$injector: ['GeolocationService']
|
||||
constructor: (@GeolocationService)->
|
||||
@$injector: ['GeolocationService', '$http']
|
||||
constructor: (@GeolocationService, @$http)->
|
||||
|
||||
getActionSheetList: ()->
|
||||
actionList = []
|
||||
actionList.push {text: "我可能喜欢的书"}
|
||||
actionList.push {text: "你可能喜欢的书"}
|
||||
@GeolocationService.getLocations (locations)=>
|
||||
locations = locations.map (location)->
|
||||
locationIds = []
|
||||
locations.map (location)->
|
||||
locationIds.push location.id
|
||||
location = {text: "#{location.address}附近流行的书"}
|
||||
actionList.push location
|
||||
localStorage.setItem 'recommend_action_sheet_arr', JSON.stringify(locationIds)
|
||||
localStorage.setItem 'recommend_action_sheet_full_arr', JSON.stringify(actionList)
|
||||
actionList
|
||||
|
||||
|
||||
popularBooksForMe: (callback, error)->
|
||||
@$http(
|
||||
url: "#{baseUrl}/recommend/me?user_email=#{email}&user_token=#{token}"
|
||||
method: 'GET'
|
||||
cache: true
|
||||
)
|
||||
.success (data, status, headers, config)->
|
||||
callback data
|
||||
.error (data)->
|
||||
error data
|
||||
|
||||
popularBooksAroundMe: (locationId, callback, error)=>
|
||||
@$http(
|
||||
url: "#{baseUrl}/recommend/locations/#{locationId}?user_email=#{email}&user_token=#{token}"
|
||||
method: 'GET'
|
||||
cache: true
|
||||
)
|
||||
.success (data, status, headers, config)->
|
||||
console.log '数据', data
|
||||
callback data
|
||||
.error (data)->
|
||||
error data
|
||||
|
||||
changeRecommendAction: (index, callback, error)=>
|
||||
if index is 0
|
||||
@popularBooksForMe callback, error
|
||||
else
|
||||
locations = JSON.parse(localStorage.getItem('recommend_action_sheet_arr'))
|
||||
@popularBooksAroundMe locations[index - 1], (result)->
|
||||
console.log 'callback....', result
|
||||
callback result
|
||||
, (errorMessage)->
|
||||
error errorMessage
|
||||
|
||||
|
||||
libr.service 'RecommendService', RecommendService
|
||||
|
||||
@@ -1,35 +1,92 @@
|
||||
// Generated by CoffeeScript 1.7.1
|
||||
(function() {
|
||||
var RecommendService, libr;
|
||||
var RecommendService, libr,
|
||||
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
|
||||
|
||||
libr = angular.module('libr.services.recommend', []);
|
||||
|
||||
RecommendService = (function() {
|
||||
RecommendService.$injector = ['GeolocationService'];
|
||||
var baseUrl, email, token;
|
||||
|
||||
function RecommendService(GeolocationService) {
|
||||
baseUrl = 'http://libr.herokuapp.com/api/v1';
|
||||
|
||||
email = localStorage.getItem('email');
|
||||
|
||||
token = localStorage.getItem('token');
|
||||
|
||||
RecommendService.$injector = ['GeolocationService', '$http'];
|
||||
|
||||
function RecommendService(GeolocationService, $http) {
|
||||
this.GeolocationService = GeolocationService;
|
||||
this.$http = $http;
|
||||
this.changeRecommendAction = __bind(this.changeRecommendAction, this);
|
||||
this.popularBooksAroundMe = __bind(this.popularBooksAroundMe, this);
|
||||
}
|
||||
|
||||
RecommendService.prototype.getActionSheetList = function() {
|
||||
var actionList;
|
||||
actionList = [];
|
||||
actionList.push({
|
||||
text: "我可能喜欢的书"
|
||||
text: "你可能喜欢的书"
|
||||
});
|
||||
this.GeolocationService.getLocations((function(_this) {
|
||||
return function(locations) {
|
||||
return locations = locations.map(function(location) {
|
||||
var locationIds;
|
||||
locationIds = [];
|
||||
locations.map(function(location) {
|
||||
locationIds.push(location.id);
|
||||
location = {
|
||||
text: "" + location.address + "附近流行的书"
|
||||
};
|
||||
return actionList.push(location);
|
||||
});
|
||||
localStorage.setItem('recommend_action_sheet_arr', JSON.stringify(locationIds));
|
||||
return localStorage.setItem('recommend_action_sheet_full_arr', JSON.stringify(actionList));
|
||||
};
|
||||
})(this));
|
||||
return actionList;
|
||||
};
|
||||
|
||||
RecommendService.prototype.popularBooksForMe = function(callback, error) {
|
||||
return this.$http({
|
||||
url: "" + baseUrl + "/recommend/me?user_email=" + email + "&user_token=" + token,
|
||||
method: 'GET',
|
||||
cache: true
|
||||
}).success(function(data, status, headers, config) {
|
||||
return callback(data);
|
||||
}).error(function(data) {
|
||||
return error(data);
|
||||
});
|
||||
};
|
||||
|
||||
RecommendService.prototype.popularBooksAroundMe = function(locationId, callback, error) {
|
||||
return this.$http({
|
||||
url: "" + baseUrl + "/recommend/locations/" + locationId + "?user_email=" + email + "&user_token=" + token,
|
||||
method: 'GET',
|
||||
cache: true
|
||||
}).success(function(data, status, headers, config) {
|
||||
console.log('数据', data);
|
||||
return callback(data);
|
||||
}).error(function(data) {
|
||||
return error(data);
|
||||
});
|
||||
};
|
||||
|
||||
RecommendService.prototype.changeRecommendAction = function(index, callback, error) {
|
||||
var locations;
|
||||
if (index === 0) {
|
||||
return this.popularBooksForMe(callback, error);
|
||||
} else {
|
||||
locations = JSON.parse(localStorage.getItem('recommend_action_sheet_arr'));
|
||||
return this.popularBooksAroundMe(locations[index - 1], function(result) {
|
||||
console.log('callback....', result);
|
||||
return callback(result);
|
||||
}, function(errorMessage) {
|
||||
return error(errorMessage);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return RecommendService;
|
||||
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
cordova.define("org.apache.cordova.inappbrowser.InAppBrowser", function(require, exports, module) { /*
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
var exec = require('cordova/exec');
|
||||
var channel = require('cordova/channel');
|
||||
var modulemapper = require('cordova/modulemapper');
|
||||
var urlutil = require('cordova/urlutil');
|
||||
|
||||
function InAppBrowser() {
|
||||
this.channels = {
|
||||
'loadstart': channel.create('loadstart'),
|
||||
'loadstop' : channel.create('loadstop'),
|
||||
'loaderror' : channel.create('loaderror'),
|
||||
'exit' : channel.create('exit')
|
||||
};
|
||||
}
|
||||
|
||||
InAppBrowser.prototype = {
|
||||
_eventHandler: function (event) {
|
||||
if (event.type in this.channels) {
|
||||
this.channels[event.type].fire(event);
|
||||
}
|
||||
},
|
||||
close: function (eventname) {
|
||||
exec(null, null, "InAppBrowser", "close", []);
|
||||
},
|
||||
show: function (eventname) {
|
||||
exec(null, null, "InAppBrowser", "show", []);
|
||||
},
|
||||
addEventListener: function (eventname,f) {
|
||||
if (eventname in this.channels) {
|
||||
this.channels[eventname].subscribe(f);
|
||||
}
|
||||
},
|
||||
removeEventListener: function(eventname, f) {
|
||||
if (eventname in this.channels) {
|
||||
this.channels[eventname].unsubscribe(f);
|
||||
}
|
||||
},
|
||||
|
||||
executeScript: function(injectDetails, cb) {
|
||||
if (injectDetails.code) {
|
||||
exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
|
||||
} else if (injectDetails.file) {
|
||||
exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
|
||||
} else {
|
||||
throw new Error('executeScript requires exactly one of code or file to be specified');
|
||||
}
|
||||
},
|
||||
|
||||
insertCSS: function(injectDetails, cb) {
|
||||
if (injectDetails.code) {
|
||||
exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
|
||||
} else if (injectDetails.file) {
|
||||
exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
|
||||
} else {
|
||||
throw new Error('insertCSS requires exactly one of code or file to be specified');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = function(strUrl, strWindowName, strWindowFeatures) {
|
||||
// Don't catch calls that write to existing frames (e.g. named iframes).
|
||||
if (window.frames && window.frames[strWindowName]) {
|
||||
var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
|
||||
return origOpenFunc.apply(window, arguments);
|
||||
}
|
||||
|
||||
strUrl = urlutil.makeAbsolute(strUrl);
|
||||
var iab = new InAppBrowser();
|
||||
var cb = function(eventname) {
|
||||
iab._eventHandler(eventname);
|
||||
};
|
||||
|
||||
exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
|
||||
return iab;
|
||||
};
|
||||
|
||||
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
<ion-view title="'Libr'" hide-back-button="false" left-buttons="leftButtons" right-buttons="rightButtons">
|
||||
<ion-view title="title" hide-back-button="false" left-buttons="leftButtons" right-buttons="rightButtons">
|
||||
<ion-content has-header="true" has-tabs="true" padding="true">
|
||||
<div class="list">
|
||||
<a ng-repeat="book in books" class="item item-thumbnail-left" href="#/book/{{book.isbn}}">
|
||||
@@ -7,6 +7,7 @@
|
||||
<h2>{{ book.name }}</h2>
|
||||
|
||||
<p>{{book.author}}</p>
|
||||
<p>有{{book.sort_id}}人看过</p>
|
||||
</a>
|
||||
</div>
|
||||
</ion-content>
|
||||
|
||||
@@ -2,18 +2,6 @@ x<ion-view title="'设置'">
|
||||
<ion-content has-header="true" has-tabs="true" padding="true">
|
||||
<div class="list">
|
||||
|
||||
<a class="item item-icon-left" href="#">
|
||||
<i class="icon ion-email"></i>
|
||||
Check mail
|
||||
<span class="badge badge-assertive">0</span>
|
||||
</a>
|
||||
|
||||
<a class="item item-icon-left item-icon-right" href="#">
|
||||
<i class="icon ion-chatbubble-working"></i>
|
||||
Call Ma
|
||||
<i class="icon ion-ios7-telephone-outline"></i>
|
||||
</a>
|
||||
|
||||
<a class="item item-icon-left">
|
||||
<i class="icon ion-person-stalker"></i>
|
||||
{{isLogedIn === true? '用户已登录': '请先登录' }}
|
||||
@@ -23,6 +11,20 @@ x<ion-view title="'设置'">
|
||||
<i class="icon ion-log-out"></i>
|
||||
注销登录
|
||||
</a>
|
||||
<a class="item item-icon-left" href="#">
|
||||
<i class="icon ion-email"></i>
|
||||
系统消息
|
||||
<span class="badge badge-assertive">0</span>
|
||||
</a>
|
||||
<a class="item item-icon-left" href="#" ng-click="feedback()">
|
||||
<i class="icon ion-heart"></i>
|
||||
给我们提供反馈
|
||||
</a>
|
||||
<a class="item item-icon-left" href="#">
|
||||
<i class="icon ion-information-circled"></i>
|
||||
关于
|
||||
</a>
|
||||
|
||||
</div>
|
||||
</ion-content>
|
||||
</ion-view>
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"prepare_queue":{"installed":[],"uninstalled":[]},"config_munge":{"framework":{"libiconv.dylib":{"false":1},"AVFoundation.framework":{"false":1},"AssetsLibrary.framework":{"false":1},"CoreVideo.framework":{"false":1},"QuartzCore.framework":{"false":1},"AudioToolbox.framework":{"false":1,"true":2}},"config.xml":{"/*":{"<feature name=\"BarcodeScanner\"><param name=\"ios-package\" value=\"CDVBarcodeScanner\" /></feature>":1,"<feature name=\"Device\"><param name=\"ios-package\" value=\"CDVDevice\" /></feature>":1,"<feature name=\"Geolocation\"><param name=\"ios-package\" value=\"CDVLocation\" /></feature>":1,"<feature name=\"Notification\"><param name=\"ios-package\" value=\"CDVNotification\" /></feature>":1,"<feature name=\"Vibration\"><param name=\"ios-package\" value=\"CDVVibration\" /></feature>":1}}},"installed_plugins":{"com.phonegap.plugins.barcodescanner":{"PACKAGE_NAME":"com.toozhao.libr"},"org.apache.cordova.device":{"PACKAGE_NAME":"com.toozhao.libr"},"org.apache.cordova.geolocation":{"PACKAGE_NAME":"com.toozhao.libr"},"org.apache.cordova.dialogs":{"PACKAGE_NAME":"com.toozhao.libr"},"org.apache.cordova.vibration":{"PACKAGE_NAME":"com.toozhao.libr"}},"dependent_plugins":{}}
|
||||
{"prepare_queue":{"installed":[],"uninstalled":[]},"config_munge":{"framework":{"libiconv.dylib":{"false":1},"AVFoundation.framework":{"false":1},"AssetsLibrary.framework":{"false":1},"CoreVideo.framework":{"false":1},"QuartzCore.framework":{"false":1},"AudioToolbox.framework":{"false":1,"true":2},"CoreGraphics.framework":{"false":1}},"config.xml":{"/*":{"<feature name=\"BarcodeScanner\"><param name=\"ios-package\" value=\"CDVBarcodeScanner\" /></feature>":1,"<feature name=\"Device\"><param name=\"ios-package\" value=\"CDVDevice\" /></feature>":1,"<feature name=\"Geolocation\"><param name=\"ios-package\" value=\"CDVLocation\" /></feature>":1,"<feature name=\"Notification\"><param name=\"ios-package\" value=\"CDVNotification\" /></feature>":1,"<feature name=\"Vibration\"><param name=\"ios-package\" value=\"CDVVibration\" /></feature>":1,"<feature name=\"InAppBrowser\"><param name=\"ios-package\" value=\"CDVInAppBrowser\" /></feature>":1}}},"installed_plugins":{"com.phonegap.plugins.barcodescanner":{"PACKAGE_NAME":"com.toozhao.libr"},"org.apache.cordova.device":{"PACKAGE_NAME":"com.toozhao.libr"},"org.apache.cordova.geolocation":{"PACKAGE_NAME":"com.toozhao.libr"},"org.apache.cordova.dialogs":{"PACKAGE_NAME":"com.toozhao.libr"},"org.apache.cordova.vibration":{"PACKAGE_NAME":"com.toozhao.libr"},"org.apache.cordova.inappbrowser":{"PACKAGE_NAME":"com.toozhao.libr"}},"dependent_plugins":{}}
|
||||
@@ -0,0 +1 @@
|
||||
{"source":{"type":"local","path":"/var/folders/gv/m43y5g9x1xdc9f2kc2p0kpz00000gn/T/org.apache.cordova.inappbrowser/package"}}
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed 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.
|
||||
@@ -0,0 +1 @@
|
||||
Icons used in ths plugin are reproduced from work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
|
||||
@@ -0,0 +1,22 @@
|
||||
<!---
|
||||
license: 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.
|
||||
-->
|
||||
|
||||
# org.apache.cordova.inappbrowser
|
||||
|
||||
Plugin documentation: [doc/index.md](doc/index.md)
|
||||
@@ -0,0 +1,75 @@
|
||||
<!--
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
-->
|
||||
# Release Notes
|
||||
|
||||
### 0.2.2 (Sept 25, 2013)
|
||||
* CB-4889 bumping&resetting version
|
||||
* CB-4788: Modified the onJsPrompt to warn against Cordova calls
|
||||
* [windows8] commandProxy was moved
|
||||
* CB-4788: Modified the onJsPrompt to warn against Cordova calls
|
||||
* [windows8] commandProxy was moved
|
||||
* CB-4889 renaming core references
|
||||
* CB-4889 renaming org.apache.cordova.core.inappbrowser to org.apache.cordova.inappbrowser
|
||||
* CB-4864, CB-4865: Minor improvements to InAppBrowser
|
||||
* Rename CHANGELOG.md -> RELEASENOTES.md
|
||||
* [CB-4792] Added keepCallback to the show function.
|
||||
* [CB-4752] Incremented plugin version on dev branch.
|
||||
|
||||
### 0.2.3 (Oct 9, 2013)
|
||||
* [CB-4915] Incremented plugin version on dev branch.
|
||||
* [CB-4926] Fixes inappbrowser plugin loading for windows8
|
||||
|
||||
### 0.2.4 (Oct 28, 2013)
|
||||
* CB-5128: added repo + issue tag to plugin.xml for inappbrowser plugin
|
||||
* CB-4995 Fix crash when WebView is quickly opened then closed.
|
||||
* CB-4930 - iOS - InAppBrowser should take into account the status bar
|
||||
* [CB-5010] Incremented plugin version on dev branch.
|
||||
* [CB-5010] Updated version and RELEASENOTES.md for release 0.2.3
|
||||
* CB-4858 - Run IAB methods on the UI thread.
|
||||
* CB-4858 Convert relative URLs to absolute URLs in JS
|
||||
* CB-3747 Fix back button having different dismiss logic from the close button.
|
||||
* CB-5021 Expose closeDialog() as a public function and make it safe to call multiple times.
|
||||
* CB-5021 Make it safe to call close() multiple times
|
||||
|
||||
### 0.2.5 (Dec 4, 2013)
|
||||
* Remove merge conflict tag
|
||||
* [CB-4724] fixed UriFormatException
|
||||
* add ubuntu platform
|
||||
* CB-3420 WP feature hidden=yes implemented
|
||||
* Added amazon-fireos platform. Change to use amazon-fireos as the platform if user agent string contains 'cordova-amazon-fireos'
|
||||
|
||||
### 0.3.0 (Jan 02, 2014)
|
||||
* CB-5592 Android: Add MIME type to Intent when opening file:/// URLs
|
||||
* CB-5594 iOS: Add disallowoverscroll option.
|
||||
* CB-5658 Add doc/index.md for InAppBrowser plugin
|
||||
* CB-5595 Add toolbarposition=top option.
|
||||
* Apply CB-5193 to InAppBrowser (Fix DB quota exception)
|
||||
* CB-5593 iOS: Make InAppBrowser localizable
|
||||
* CB-5591 Change window.escape to encodeURIComponent
|
||||
|
||||
### 0.3.1 (Feb 05, 2014)
|
||||
* CB-5756: Android: Use WebView.evaluateJavascript for script injection on Android 4.4+
|
||||
* Didn't test on ICS or lower, getDrawable isn't supported until Jellybean
|
||||
* add ubuntu platform
|
||||
* Adding drawables to the inAppBrowser. This doesn't look quite right, but it's a HUGE improvement over the previous settings
|
||||
* CB-5756: Android: Use WebView.evaluateJavascript for script injection on Android 4.4+
|
||||
* Remove alive from InAppBrowser.js since it didn't catch the case where the browser is closed by the user.
|
||||
* CB-5733 Fix IAB.close() not working if called before show() animation is done
|
||||
@@ -0,0 +1,280 @@
|
||||
<!---
|
||||
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.
|
||||
-->
|
||||
|
||||
# org.apache.cordova.inappbrowser
|
||||
|
||||
This plugin provides a web browser view that displays when calling `window.open()`, or when opening a link formed as `<a target="_blank">`.
|
||||
|
||||
var ref = window.open('http://apache.org', '_blank', 'location=yes');
|
||||
|
||||
__NOTE__: The InAppBrowser window behaves like a standard web browser,
|
||||
and can't access Cordova APIs.
|
||||
|
||||
## Installation
|
||||
|
||||
cordova plugin add org.apache.cordova.inappbrowser
|
||||
|
||||
## window.open
|
||||
|
||||
Opens a URL in a new `InAppBrowser` instance, the current browser
|
||||
instance, or the system browser.
|
||||
|
||||
var ref = window.open(url, target, options);
|
||||
|
||||
- __ref__: Reference to the `InAppBrowser` window. _(InAppBrowser)_
|
||||
|
||||
- __url__: The URL to load _(String)_. Call `encodeURI()` on this if the URL contains Unicode characters.
|
||||
|
||||
- __target__: The target in which to load the URL, an optional parameter that defaults to `_self`. _(String)_
|
||||
|
||||
- `_self`: Opens in the Cordova WebView if the URL is in the white list, otherwise it opens in the `InAppBrowser`.
|
||||
- `_blank`: Opens in the `InAppBrowser`.
|
||||
- `_system`: Opens in the system's web browser.
|
||||
|
||||
- __options__: Options for the `InAppBrowser`. Optional, defaulting to: `location=yes`. _(String)_
|
||||
|
||||
The `options` string must not contain any blank space, and each feature's name/value pairs must be separated by a comma. Feature names are case insensitive. All platforms support the value below:
|
||||
|
||||
- __location__: Set to `yes` or `no` to turn the `InAppBrowser`'s location bar on or off.
|
||||
|
||||
Android only:
|
||||
|
||||
- __closebuttoncaption__: set to a string to use as the __Done__ button's caption.
|
||||
- __hidden__: set to `yes` to create the browser and load the page, but not show it. The load event fires when loading is complete. Omit or set to `no` (default) to have the browser open and load normally.
|
||||
- __clearcache__: set to `yes` to have the browser's cookie cache cleared before the new window is opened
|
||||
- __clearsessioncache__: set to `yes` to have the session cookie cache cleared before the new window is opened
|
||||
|
||||
iOS only:
|
||||
|
||||
- __closebuttoncaption__: set to a string to use as the __Done__ button's caption. Note that you need to localize this value yourself.
|
||||
- __disallowoverscroll__: Set to `yes` or `no` (default is `no`). Turns on/off the UIWebViewBounce property.
|
||||
- __hidden__: set to `yes` to create the browser and load the page, but not show it. The load event fires when loading is complete. Omit or set to `no` (default) to have the browser open and load normally.
|
||||
- __toolbar__: set to `yes` or `no` to turn the toolbar on or off for the InAppBrowser (defaults to `yes`)
|
||||
- __enableViewportScale__: Set to `yes` or `no` to prevent viewport scaling through a meta tag (defaults to `no`).
|
||||
- __mediaPlaybackRequiresUserAction__: Set to `yes` or `no` to prevent HTML5 audio or video from autoplaying (defaults to `no`).
|
||||
- __allowInlineMediaPlayback__: Set to `yes` or `no` to allow in-line HTML5 media playback, displaying within the browser window rather than a device-specific playback interface. The HTML's `video` element must also include the `webkit-playsinline` attribute (defaults to `no`)
|
||||
- __keyboardDisplayRequiresUserAction__: Set to `yes` or `no` to open the keyboard when form elements receive focus via JavaScript's `focus()` call (defaults to `yes`).
|
||||
- __suppressesIncrementalRendering__: Set to `yes` or `no` to wait until all new view content is received before being rendered (defaults to `no`).
|
||||
- __presentationstyle__: Set to `pagesheet`, `formsheet` or `fullscreen` to set the [presentation style](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle) (defaults to `fullscreen`).
|
||||
- __transitionstyle__: Set to `fliphorizontal`, `crossdissolve` or `coververtical` to set the [transition style](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle) (defaults to `coververtical`).
|
||||
- __toolbarposition__: Set to `top` or `bottom` (default is `bottom`). Causes the toolbar to be at the top or bottom of the window.
|
||||
|
||||
### Supported Platforms
|
||||
|
||||
- Amazon Fire OS
|
||||
- Android
|
||||
- BlackBerry 10
|
||||
- iOS
|
||||
- Windows Phone 7 and 8
|
||||
|
||||
### Example
|
||||
|
||||
var ref = window.open('http://apache.org', '_blank', 'location=yes');
|
||||
var ref2 = window.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
|
||||
|
||||
## InAppBrowser
|
||||
|
||||
The object returned from a call to `window.open`.
|
||||
|
||||
### Methods
|
||||
|
||||
- addEventListener
|
||||
- removeEventListener
|
||||
- close
|
||||
- show
|
||||
- executeScript
|
||||
- insertCSS
|
||||
|
||||
## addEventListener
|
||||
|
||||
> Adds a listener for an event from the `InAppBrowser`.
|
||||
|
||||
ref.addEventListener(eventname, callback);
|
||||
|
||||
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
|
||||
|
||||
- __eventname__: the event to listen for _(String)_
|
||||
|
||||
- __loadstart__: event fires when the `InAppBrowser` starts to load a URL.
|
||||
- __loadstop__: event fires when the `InAppBrowser` finishes loading a URL.
|
||||
- __loaderror__: event fires when the `InAppBrowser` encounters an error when loading a URL.
|
||||
- __exit__: event fires when the `InAppBrowser` window is closed.
|
||||
|
||||
- __callback__: the function that executes when the event fires. The function is passed an `InAppBrowserEvent` object as a parameter.
|
||||
|
||||
### InAppBrowserEvent Properties
|
||||
|
||||
- __type__: the eventname, either `loadstart`, `loadstop`, `loaderror`, or `exit`. _(String)_
|
||||
|
||||
- __url__: the URL that was loaded. _(String)_
|
||||
|
||||
- __code__: the error code, only in the case of `loaderror`. _(Number)_
|
||||
|
||||
- __message__: the error message, only in the case of `loaderror`. _(String)_
|
||||
|
||||
|
||||
### Supported Platforms
|
||||
|
||||
- Amazon Fire OS
|
||||
- Android
|
||||
- BlackBerry 10
|
||||
- iOS
|
||||
- Windows Phone 7 and 8
|
||||
|
||||
### Quick Example
|
||||
|
||||
var ref = window.open('http://apache.org', '_blank', 'location=yes');
|
||||
ref.addEventListener('loadstart', function() { alert(event.url); });
|
||||
|
||||
## removeEventListener
|
||||
|
||||
> Removes a listener for an event from the `InAppBrowser`.
|
||||
|
||||
ref.removeEventListener(eventname, callback);
|
||||
|
||||
- __ref__: reference to the `InAppBrowser` window. _(InAppBrowser)_
|
||||
|
||||
- __eventname__: the event to stop listening for. _(String)_
|
||||
|
||||
- __loadstart__: event fires when the `InAppBrowser` starts to load a URL.
|
||||
- __loadstop__: event fires when the `InAppBrowser` finishes loading a URL.
|
||||
- __loaderror__: event fires when the `InAppBrowser` encounters an error loading a URL.
|
||||
- __exit__: event fires when the `InAppBrowser` window is closed.
|
||||
|
||||
- __callback__: the function to execute when the event fires.
|
||||
The function is passed an `InAppBrowserEvent` object.
|
||||
|
||||
### Supported Platforms
|
||||
|
||||
- Amazon Fire OS
|
||||
- Android
|
||||
- BlackBerry 10
|
||||
- iOS
|
||||
- Windows Phone 7 and 8
|
||||
|
||||
### Quick Example
|
||||
|
||||
var ref = window.open('http://apache.org', '_blank', 'location=yes');
|
||||
var myCallback = function() { alert(event.url); }
|
||||
ref.addEventListener('loadstart', myCallback);
|
||||
ref.removeEventListener('loadstart', myCallback);
|
||||
|
||||
## close
|
||||
|
||||
> Closes the `InAppBrowser` window.
|
||||
|
||||
ref.close();
|
||||
|
||||
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
|
||||
|
||||
### Supported Platforms
|
||||
|
||||
- Amazon Fire OS
|
||||
- Android
|
||||
- BlackBerry 10
|
||||
- iOS
|
||||
- Windows Phone 7 and 8
|
||||
|
||||
### Quick Example
|
||||
|
||||
var ref = window.open('http://apache.org', '_blank', 'location=yes');
|
||||
ref.close();
|
||||
|
||||
## show
|
||||
|
||||
> Displays an InAppBrowser window that was opened hidden. Calling this has no effect if the InAppBrowser was already visible.
|
||||
|
||||
ref.show();
|
||||
|
||||
- __ref__: reference to the InAppBrowser window (`InAppBrowser`)
|
||||
|
||||
### Supported Platforms
|
||||
|
||||
- Amazon Fire OS
|
||||
- Android
|
||||
- BlackBerry 10
|
||||
- iOS
|
||||
|
||||
### Quick Example
|
||||
|
||||
var ref = window.open('http://apache.org', '_blank', 'hidden=yes');
|
||||
// some time later...
|
||||
ref.show();
|
||||
|
||||
## executeScript
|
||||
|
||||
> Injects JavaScript code into the `InAppBrowser` window
|
||||
|
||||
ref.executeScript(details, callback);
|
||||
|
||||
- __ref__: reference to the `InAppBrowser` window. _(InAppBrowser)_
|
||||
|
||||
- __injectDetails__: details of the script to run, specifying either a `file` or `code` key. _(Object)_
|
||||
- __file__: URL of the script to inject.
|
||||
- __code__: Text of the script to inject.
|
||||
|
||||
- __callback__: the function that executes after the JavaScript code is injected.
|
||||
- If the injected script is of type `code`, the callback executes
|
||||
with a single parameter, which is the return value of the
|
||||
script, wrapped in an `Array`. For multi-line scripts, this is
|
||||
the return value of the last statement, or the last expression
|
||||
evaluated.
|
||||
|
||||
### Supported Platforms
|
||||
|
||||
- Amazon Fire OS
|
||||
- Android
|
||||
- BlackBerry 10
|
||||
- iOS
|
||||
|
||||
### Quick Example
|
||||
|
||||
var ref = window.open('http://apache.org', '_blank', 'location=yes');
|
||||
ref.addEventListener('loadstop', function() {
|
||||
ref.executeScript({file: "myscript.js"});
|
||||
});
|
||||
|
||||
## insertCSS
|
||||
|
||||
> Injects CSS into the `InAppBrowser` window.
|
||||
|
||||
ref.insertCSS(details, callback);
|
||||
|
||||
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
|
||||
|
||||
- __injectDetails__: details of the script to run, specifying either a `file` or `code` key. _(Object)_
|
||||
- __file__: URL of the stylesheet to inject.
|
||||
- __code__: Text of the stylesheet to inject.
|
||||
|
||||
- __callback__: the function that executes after the CSS is injected.
|
||||
|
||||
### Supported Platforms
|
||||
|
||||
- Amazon Fire OS
|
||||
- Android
|
||||
- BlackBerry 10
|
||||
- iOS
|
||||
|
||||
### Quick Example
|
||||
|
||||
var ref = window.open('http://apache.org', '_blank', 'location=yes');
|
||||
ref.addEventListener('loadstop', function() {
|
||||
ref.insertCSS({file: "mystyles.css"});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"version": "0.3.1",
|
||||
"name": "org.apache.cordova.inappbrowser",
|
||||
"cordova_name": "InAppBrowser",
|
||||
"description": "Cordova InAppBrowser Plugin",
|
||||
"license": "Apache 2.0",
|
||||
"repo": "https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser.git",
|
||||
"issue": "https://issues.apache.org/jira/browse/CB/component/12320641",
|
||||
"keywords": [
|
||||
"cordova",
|
||||
"in",
|
||||
"app",
|
||||
"browser",
|
||||
"inappbrowser"
|
||||
],
|
||||
"engines": [
|
||||
{
|
||||
"name": "cordova",
|
||||
"version": ">=3.1.0"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
|
||||
id="org.apache.cordova.inappbrowser"
|
||||
version="0.3.1">
|
||||
|
||||
<name>InAppBrowser</name>
|
||||
<description>Cordova InAppBrowser Plugin</description>
|
||||
<license>Apache 2.0</license>
|
||||
<keywords>cordova,in,app,browser,inappbrowser</keywords>
|
||||
<repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser.git</repo>
|
||||
<issue>https://issues.apache.org/jira/browse/CB/component/12320641</issue>
|
||||
|
||||
<engines>
|
||||
<engine name="cordova" version=">=3.1.0" /><!-- Needs cordova/urlutil -->
|
||||
</engines>
|
||||
|
||||
<js-module src="www/InAppBrowser.js" name="InAppBrowser">
|
||||
<clobbers target="window.open" />
|
||||
</js-module>
|
||||
|
||||
<!-- -->
|
||||
<platform name="android">
|
||||
<config-file target="res/xml/config.xml" parent="/*">
|
||||
<feature name="InAppBrowser">
|
||||
<param name="android-package" value="org.apache.cordova.inappbrowser.InAppBrowser"/>
|
||||
</feature>
|
||||
</config-file>
|
||||
|
||||
<source-file src="src/android/InAppBrowser.java" target-dir="src/org/apache/cordova/inappbrowser" />
|
||||
<source-file src="src/android/InAppChromeClient.java" target-dir="src/org/apache/cordova/inappbrowser" />
|
||||
|
||||
<!-- drawable src/android/resources -->
|
||||
<resource-file src="src/android/res/drawable-hdpi/ic_action_next_item.png" target="res/drawable-hdpi/ic_action_next_item.png" />
|
||||
<resource-file src="src/android/res/drawable-mdpi/ic_action_next_item.png" target="res/drawable-mdpi/ic_action_next_item.png" />
|
||||
<resource-file src="src/android/res/drawable-xhdpi/ic_action_next_item.png" target="res/drawable-xhdpi/ic_action_next_item.png" />
|
||||
<resource-file src="src/android/res/drawable-xxhdpi/ic_action_next_item.png" target="res/drawable-xxhdpi/ic_action_next_item.png" />
|
||||
|
||||
<resource-file src="src/android/res/drawable-hdpi/ic_action_previous_item.png" target="res/drawable-hdpi/ic_action_previous_item.png" />
|
||||
<resource-file src="src/android/res/drawable-mdpi/ic_action_previous_item.png" target="res/drawable-mdpi/ic_action_previous_item.png" />
|
||||
<resource-file src="src/android/res/drawable-xhdpi/ic_action_previous_item.png" target="res/drawable-xhdpi/ic_action_previous_item.png" />
|
||||
<resource-file src="src/android/res/drawable-xxhdpi/ic_action_previous_item.png" target="res/drawable-xxhdpi/ic_action_previous_item.png" />
|
||||
|
||||
<resource-file src="src/android/res/drawable-hdpi/ic_action_remove.png" target="res/drawable-hdpi/ic_action_remove.png" />
|
||||
<resource-file src="src/android/res/drawable-mdpi/ic_action_remove.png" target="res/drawable-mdpi/ic_action_remove.png" />
|
||||
<resource-file src="src/android/res/drawable-xhdpi/ic_action_remove.png" target="res/drawable-xhdpi/ic_action_remove.png" />
|
||||
<resource-file src="src/android/res/drawable-xxhdpi/ic_action_remove.png" target="res/drawable-xxhdpi/ic_action_remove.png" />
|
||||
|
||||
</platform>
|
||||
|
||||
<!-- amazon-fireos -->
|
||||
<platform name="amazon-fireos">
|
||||
<config-file target="res/xml/config.xml" parent="/*">
|
||||
<feature name="InAppBrowser">
|
||||
<param name="android-package" value="org.apache.cordova.inappbrowser.InAppBrowser"/>
|
||||
</feature>
|
||||
</config-file>
|
||||
|
||||
<source-file src="src/amazon/InAppBrowser.java" target-dir="src/org/apache/cordova/inappbrowser" />
|
||||
<source-file src="src/amazon/InAppChromeClient.java" target-dir="src/org/apache/cordova/inappbrowser" />
|
||||
</platform>
|
||||
|
||||
<!-- ubuntu -->
|
||||
<platform name="ubuntu">
|
||||
<header-file src="src/ubuntu/inappbrowser.h" />
|
||||
<source-file src="src/ubuntu/inappbrowser.cpp" />
|
||||
<resource-file src="src/ubuntu/InAppBrowser.qml" />
|
||||
<resource-file src="src/ubuntu/close.png" />
|
||||
</platform>
|
||||
|
||||
<!-- ios -->
|
||||
<platform name="ios">
|
||||
<config-file target="config.xml" parent="/*">
|
||||
<feature name="InAppBrowser">
|
||||
<param name="ios-package" value="CDVInAppBrowser" />
|
||||
</feature>
|
||||
</config-file>
|
||||
|
||||
<header-file src="src/ios/CDVInAppBrowser.h" />
|
||||
<source-file src="src/ios/CDVInAppBrowser.m" />
|
||||
|
||||
<framework src="CoreGraphics.framework" />
|
||||
</platform>
|
||||
|
||||
<!-- blackberry10 -->
|
||||
<!-- <platform name="blackberry10">
|
||||
<config-file target="www/config.xml" parent="/widget">
|
||||
<feature name="InAppBrowser" value="InAppBrowser"/>
|
||||
</config-file>
|
||||
</platform>
|
||||
-->
|
||||
<!-- wp7 -->
|
||||
<platform name="wp7">
|
||||
<config-file target="config.xml" parent="/*">
|
||||
<feature name="InAppBrowser">
|
||||
<param name="wp-package" value="InAppBrowser"/>
|
||||
</feature>
|
||||
</config-file>
|
||||
|
||||
<source-file src="src/wp/InAppBrowser.cs" />
|
||||
</platform>
|
||||
|
||||
<!-- wp8 -->
|
||||
<platform name="wp8">
|
||||
<config-file target="config.xml" parent="/*">
|
||||
<feature name="InAppBrowser">
|
||||
<param name="wp-package" value="InAppBrowser"/>
|
||||
</feature>
|
||||
</config-file>
|
||||
|
||||
<source-file src="src/wp/InAppBrowser.cs" />
|
||||
</platform>
|
||||
|
||||
<!-- windows8 -->
|
||||
<platform name="windows8">
|
||||
<js-module src="www/windows8/InAppBrowserProxy.js" name="InAppBrowserProxy">
|
||||
<merges target="" />
|
||||
</js-module>
|
||||
</platform>
|
||||
|
||||
|
||||
</plugin>
|
||||
@@ -0,0 +1,769 @@
|
||||
/*
|
||||
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.annotation.SuppressLint;
|
||||
import android.app.Dialog;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
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 com.amazon.android.webkit.AmazonWebChromeClient;
|
||||
import com.amazon.android.webkit.AmazonGeolocationPermissions.Callback;
|
||||
import com.amazon.android.webkit.AmazonJsPromptResult;
|
||||
import com.amazon.android.webkit.AmazonWebSettings;
|
||||
import com.amazon.android.webkit.AmazonWebStorage;
|
||||
import com.amazon.android.webkit.AmazonWebView;
|
||||
import com.amazon.android.webkit.AmazonWebViewClient;
|
||||
import com.amazon.android.webkit.AmazonCookieManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.RelativeLayout;
|
||||
|
||||
import org.apache.cordova.CallbackContext;
|
||||
import org.apache.cordova.Config;
|
||||
import org.apache.cordova.CordovaArgs;
|
||||
import org.apache.cordova.CordovaPlugin;
|
||||
import org.apache.cordova.CordovaWebView;
|
||||
import org.apache.cordova.LOG;
|
||||
import org.apache.cordova.PluginResult;
|
||||
import org.apache.cordova.CordovaActivity;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
@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 BLANK = "_blank";
|
||||
private static final String EXIT_EVENT = "exit";
|
||||
private static final String LOCATION = "location";
|
||||
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 CLOSE_BUTTON_CAPTION = "closebuttoncaption";
|
||||
private static final String CLEAR_ALL_CACHE = "clearcache";
|
||||
private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
|
||||
|
||||
private Dialog dialog;
|
||||
private AmazonWebView inAppWebView;
|
||||
private EditText edittext;
|
||||
private CallbackContext callbackContext;
|
||||
private boolean showLocationBar = true;
|
||||
private boolean openWindowHidden = false;
|
||||
private String buttonLabel = "Done";
|
||||
private boolean clearAllCache= false;
|
||||
private boolean clearSessionCache=false;
|
||||
|
||||
/**
|
||||
* Executes the request and returns PluginResult.
|
||||
*
|
||||
* @param action The action to execute.
|
||||
* @param args JSONArry of arguments for the plugin.
|
||||
* @param callbackId The callback id 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, Boolean> 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");
|
||||
// load in webview
|
||||
if (url.startsWith("file://") || url.startsWith("javascript:")
|
||||
|| Config.isUrlWhiteListed(url)) {
|
||||
webView.loadUrl(url);
|
||||
}
|
||||
//Load the dialer
|
||||
else if (url.startsWith(AmazonWebView.SCHEME_TEL))
|
||||
{
|
||||
try {
|
||||
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 {
|
||||
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("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 {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the view navigates.
|
||||
*/
|
||||
@Override
|
||||
public void onReset() {
|
||||
closeDialog();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 AmazonWebView.
|
||||
*
|
||||
* 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) {
|
||||
final 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 action will have the side-effect of blurring the currently focused element
|
||||
this.cordova.getActivity().runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
inAppWebView.loadUrl("javascript:" + finalScriptToInject);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the list of features into a hash map
|
||||
*
|
||||
* @param optString
|
||||
* @return
|
||||
*/
|
||||
private HashMap<String, Boolean> parseFeature(String optString) {
|
||||
if (optString.equals(NULL)) {
|
||||
return null;
|
||||
} else {
|
||||
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
|
||||
StringTokenizer features = new StringTokenizer(optString, ",");
|
||||
StringTokenizer option;
|
||||
while(features.hasMoreElements()) {
|
||||
option = new StringTokenizer(features.nextToken(), "=");
|
||||
if (option.hasMoreElements()) {
|
||||
String key = option.nextToken();
|
||||
if (key.equalsIgnoreCase(CLOSE_BUTTON_CAPTION)) {
|
||||
this.buttonLabel = option.nextToken();
|
||||
} else {
|
||||
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
|
||||
map.put(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a new browser with the specified URL.
|
||||
*
|
||||
* @param url The url to load.
|
||||
* @param usePhoneGap Load url in PhoneGap webview
|
||||
* @return "" if ok, or error message.
|
||||
*/
|
||||
public String openExternal(String url) {
|
||||
try {
|
||||
Intent intent = null;
|
||||
intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setData(Uri.parse(url));
|
||||
this.cordova.getActivity().startActivity(intent);
|
||||
return "";
|
||||
} catch (android.content.ActivityNotFoundException 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() {
|
||||
public void run() {
|
||||
if (dialog != null) {
|
||||
dialog.dismiss();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if it is possible to go back one page in history, then does so.
|
||||
*/
|
||||
private void goBack() {
|
||||
this.cordova.getActivity().runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
if (InAppBrowser.this.inAppWebView.canGoBack()) {
|
||||
InAppBrowser.this.inAppWebView.goBack();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if it is possible to go forward one page in history, then does so.
|
||||
*/
|
||||
private void goForward() {
|
||||
this.cordova.getActivity().runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
if (InAppBrowser.this.inAppWebView.canGoForward()) {
|
||||
InAppBrowser.this.inAppWebView.goForward();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to the new page
|
||||
*
|
||||
* @param url to load
|
||||
*/
|
||||
private void navigate(final String url) {
|
||||
InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
|
||||
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
|
||||
|
||||
this.cordova.getActivity().runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
if (!url.startsWith("http") && !url.startsWith("file:")) {
|
||||
InAppBrowser.this.inAppWebView.loadUrl("http://" + url);
|
||||
} else {
|
||||
InAppBrowser.this.inAppWebView.loadUrl(url);
|
||||
}
|
||||
InAppBrowser.this.inAppWebView.requestFocus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Should we show the location bar?
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
private boolean getShowLocationBar() {
|
||||
return this.showLocationBar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a new browser with the specified URL.
|
||||
*
|
||||
* @param url The url to load.
|
||||
* @param jsonObject
|
||||
*/
|
||||
public String showWebPage(final String url, HashMap<String, Boolean> features) {
|
||||
// Determine if we should hide the location bar.
|
||||
showLocationBar = true;
|
||||
openWindowHidden = false;
|
||||
if (features != null) {
|
||||
Boolean show = features.get(LOCATION);
|
||||
if (show != null) {
|
||||
showLocationBar = show.booleanValue();
|
||||
}
|
||||
Boolean hidden = features.get(HIDDEN);
|
||||
if (hidden != null) {
|
||||
openWindowHidden = hidden.booleanValue();
|
||||
}
|
||||
Boolean cache = features.get(CLEAR_ALL_CACHE);
|
||||
if (cache != null) {
|
||||
clearAllCache = cache.booleanValue();
|
||||
} else {
|
||||
cache = features.get(CLEAR_SESSION_CACHE);
|
||||
if (cache != null) {
|
||||
clearSessionCache = cache.booleanValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
// Let's create the main dialog
|
||||
dialog = new Dialog(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.setOnDismissListener(new DialogInterface.OnDismissListener() {
|
||||
public void onDismiss(DialogInterface dialog) {
|
||||
closeDialog();
|
||||
}
|
||||
});
|
||||
|
||||
// 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(android.graphics.Color.LTGRAY);
|
||||
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(1);
|
||||
|
||||
// Back button
|
||||
Button back = new Button(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(2);
|
||||
back.setText("<");
|
||||
back.setOnClickListener(new View.OnClickListener() {
|
||||
public void onClick(View v) {
|
||||
goBack();
|
||||
}
|
||||
});
|
||||
|
||||
// Forward button
|
||||
Button forward = new Button(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(3);
|
||||
forward.setText(">");
|
||||
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(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;
|
||||
}
|
||||
});
|
||||
|
||||
// Close button
|
||||
Button close = new Button(cordova.getActivity());
|
||||
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
|
||||
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
|
||||
close.setLayoutParams(closeLayoutParams);
|
||||
forward.setContentDescription("Close Button");
|
||||
close.setId(5);
|
||||
close.setText(buttonLabel);
|
||||
close.setOnClickListener(new View.OnClickListener() {
|
||||
public void onClick(View v) {
|
||||
closeDialog();
|
||||
}
|
||||
});
|
||||
|
||||
// WebView
|
||||
inAppWebView = new AmazonWebView(cordova.getActivity());
|
||||
|
||||
CordovaActivity app = (CordovaActivity) cordova.getActivity();
|
||||
cordova.getFactory().initializeWebView(inAppWebView, 0x00FF00, false, null);
|
||||
|
||||
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
|
||||
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
|
||||
AmazonWebViewClient client = new InAppBrowserClient(thatWebView, edittext);
|
||||
inAppWebView.setWebViewClient(client);
|
||||
AmazonWebSettings settings = inAppWebView.getSettings();
|
||||
settings.setJavaScriptEnabled(true);
|
||||
settings.setJavaScriptCanOpenWindowsAutomatically(true);
|
||||
settings.setBuiltInZoomControls(true);
|
||||
settings.setPluginState(com.amazon.android.webkit.AmazonWebSettings.PluginState.ON);
|
||||
|
||||
//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) {
|
||||
AmazonCookieManager.getInstance().removeAllCookie();
|
||||
} else if (clearSessionCache) {
|
||||
AmazonCookieManager.getInstance().removeSessionCookie();
|
||||
}
|
||||
|
||||
inAppWebView.loadUrl(url);
|
||||
inAppWebView.setId(6);
|
||||
inAppWebView.getSettings().setLoadWithOverviewMode(true);
|
||||
inAppWebView.getSettings().setUseWideViewPort(true);
|
||||
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
|
||||
toolbar.addView(actionButtonContainer);
|
||||
toolbar.addView(edittext);
|
||||
toolbar.addView(close);
|
||||
|
||||
// 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
|
||||
main.addView(inAppWebView);
|
||||
|
||||
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 "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The webview client receives notifications about appView
|
||||
*/
|
||||
public class InAppBrowserClient extends AmazonWebViewClient {
|
||||
EditText edittext;
|
||||
CordovaWebView webView;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param mContext
|
||||
* @param edittext
|
||||
*/
|
||||
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
|
||||
this.webView = webView;
|
||||
this.edittext = mEditText;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the host application that a page has started loading.
|
||||
*
|
||||
* @param view The webview initiating the callback.
|
||||
* @param url The url of the page.
|
||||
*/
|
||||
@Override
|
||||
public void onPageStarted(AmazonWebView view, String url, Bitmap favicon) {
|
||||
super.onPageStarted(view, url, favicon);
|
||||
String newloc = "";
|
||||
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
|
||||
newloc = url;
|
||||
}
|
||||
// If dialing phone (tel:5551212)
|
||||
else if (url.startsWith(AmazonWebView.SCHEME_TEL)) {
|
||||
try {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
else if (url.startsWith("geo:") || url.startsWith(AmazonWebView.SCHEME_MAILTO) || url.startsWith("market:")) {
|
||||
try {
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setData(Uri.parse(url));
|
||||
cordova.getActivity().startActivity(intent);
|
||||
} 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);
|
||||
} catch (android.content.ActivityNotFoundException e) {
|
||||
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
|
||||
}
|
||||
}
|
||||
else {
|
||||
newloc = "http://" + url;
|
||||
}
|
||||
|
||||
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.d(LOG_TAG, "Should never happen");
|
||||
}
|
||||
}
|
||||
|
||||
public void onPageFinished(AmazonWebView view, String url) {
|
||||
super.onPageFinished(view, url);
|
||||
|
||||
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(AmazonWebView 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");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package org.apache.cordova.inappbrowser;
|
||||
|
||||
import org.apache.cordova.CordovaWebView;
|
||||
import org.apache.cordova.LOG;
|
||||
import org.apache.cordova.PluginResult;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
|
||||
import com.amazon.android.webkit.AmazonWebChromeClient;
|
||||
import com.amazon.android.webkit.AmazonGeolocationPermissions.Callback;
|
||||
import com.amazon.android.webkit.AmazonJsPromptResult;
|
||||
import com.amazon.android.webkit.AmazonWebStorage;
|
||||
import com.amazon.android.webkit.AmazonWebView;
|
||||
import com.amazon.android.webkit.AmazonWebViewClient;
|
||||
|
||||
public class InAppChromeClient extends AmazonWebChromeClient {
|
||||
|
||||
private CordovaWebView webView;
|
||||
private String LOG_TAG = "InAppChromeClient";
|
||||
private long MAX_QUOTA = 100 * 1024 * 1024;
|
||||
|
||||
public InAppChromeClient(CordovaWebView webView) {
|
||||
super();
|
||||
this.webView = webView;
|
||||
}
|
||||
/**
|
||||
* Handle database quota exceeded notification.
|
||||
*
|
||||
* @param url
|
||||
* @param databaseIdentifier
|
||||
* @param currentQuota
|
||||
* @param estimatedSize
|
||||
* @param totalUsedQuota
|
||||
* @param quotaUpdater
|
||||
*/
|
||||
@Override
|
||||
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
|
||||
long totalUsedQuota, AmazonWebStorage.QuotaUpdater quotaUpdater)
|
||||
{
|
||||
LOG.d(LOG_TAG, "onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
|
||||
|
||||
if (estimatedSize < MAX_QUOTA)
|
||||
{
|
||||
//increase for 1Mb
|
||||
long newQuota = estimatedSize;
|
||||
LOG.d(LOG_TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota);
|
||||
quotaUpdater.updateQuota(newQuota);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Set the quota to whatever it is and force an error
|
||||
// TODO: get docs on how to handle this properly
|
||||
quotaUpdater.updateQuota(currentQuota);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.
|
||||
*
|
||||
* @param origin
|
||||
* @param callback
|
||||
*/
|
||||
@Override
|
||||
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
|
||||
super.onGeolocationPermissionsShowPrompt(origin, callback);
|
||||
callback.invoke(origin, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell the client to display a prompt dialog to the user.
|
||||
* If the client returns true, WebView will assume that the client will
|
||||
* handle the prompt dialog and call the appropriate JsPromptResult method.
|
||||
*
|
||||
* The prompt bridge provided for the InAppBrowser is capable of executing any
|
||||
* oustanding callback belonging to the InAppBrowser plugin. Care has been
|
||||
* taken that other callbacks cannot be triggered, and that no other code
|
||||
* execution is possible.
|
||||
*
|
||||
* To trigger the bridge, the prompt default value should be of the form:
|
||||
*
|
||||
* gap-iab://<callbackId>
|
||||
*
|
||||
* where <callbackId> is the string id of the callback to trigger (something
|
||||
* like "InAppBrowser0123456789")
|
||||
*
|
||||
* If present, the prompt message is expected to be a JSON-encoded value to
|
||||
* pass to the callback. A JSON_EXCEPTION is returned if the JSON is invalid.
|
||||
*
|
||||
* @param view
|
||||
* @param url
|
||||
* @param message
|
||||
* @param defaultValue
|
||||
* @param result
|
||||
*/
|
||||
@Override
|
||||
public boolean onJsPrompt(AmazonWebView view, String url, String message, String defaultValue, AmazonJsPromptResult result) {
|
||||
// See if the prompt string uses the 'gap-iab' protocol. If so, the remainder should be the id of a callback to execute.
|
||||
if (defaultValue != null && defaultValue.startsWith("gap")) {
|
||||
if(defaultValue.startsWith("gap-iab://")) {
|
||||
PluginResult scriptResult;
|
||||
String scriptCallbackId = defaultValue.substring(10);
|
||||
if (scriptCallbackId.startsWith("InAppBrowser")) {
|
||||
if(message == null || message.length() == 0) {
|
||||
scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray());
|
||||
} else {
|
||||
try {
|
||||
scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray(message));
|
||||
} catch(JSONException e) {
|
||||
scriptResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
|
||||
}
|
||||
}
|
||||
this.webView.sendPluginResult(scriptResult, scriptCallbackId);
|
||||
result.confirm("");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Anything else with a gap: prefix should get this message
|
||||
LOG.w(LOG_TAG, "InAppBrowser does not support Cordova API calls: " + url + " " + defaultValue);
|
||||
result.cancel();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,811 @@
|
||||
/*
|
||||
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.annotation.SuppressLint;
|
||||
import android.app.Dialog;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
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.WebSettings;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.RelativeLayout;
|
||||
|
||||
import org.apache.cordova.CallbackContext;
|
||||
import org.apache.cordova.Config;
|
||||
import org.apache.cordova.CordovaArgs;
|
||||
import org.apache.cordova.CordovaPlugin;
|
||||
import org.apache.cordova.CordovaWebView;
|
||||
import org.apache.cordova.LOG;
|
||||
import org.apache.cordova.PluginResult;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
@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 BLANK = "_blank";
|
||||
private static final String EXIT_EVENT = "exit";
|
||||
private static final String LOCATION = "location";
|
||||
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 CLOSE_BUTTON_CAPTION = "closebuttoncaption";
|
||||
private static final String CLEAR_ALL_CACHE = "clearcache";
|
||||
private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
|
||||
|
||||
private Dialog dialog;
|
||||
private WebView inAppWebView;
|
||||
private EditText edittext;
|
||||
private CallbackContext callbackContext;
|
||||
private boolean showLocationBar = true;
|
||||
private boolean openWindowHidden = false;
|
||||
private String buttonLabel = "Done";
|
||||
private boolean clearAllCache= false;
|
||||
private boolean clearSessionCache=false;
|
||||
|
||||
/**
|
||||
* Executes the request and returns PluginResult.
|
||||
*
|
||||
* @param action The action to execute.
|
||||
* @param args JSONArry of arguments for the plugin.
|
||||
* @param callbackId The callback id 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, Boolean> 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");
|
||||
// load in webview
|
||||
if (url.startsWith("file://") || url.startsWith("javascript:")
|
||||
|| Config.isUrlWhiteListed(url)) {
|
||||
webView.loadUrl(url);
|
||||
}
|
||||
//Load the dialer
|
||||
else if (url.startsWith(WebView.SCHEME_TEL))
|
||||
{
|
||||
try {
|
||||
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 {
|
||||
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("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 {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the view navigates.
|
||||
*/
|
||||
@Override
|
||||
public void onReset() {
|
||||
closeDialog();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the list of features into a hash map
|
||||
*
|
||||
* @param optString
|
||||
* @return
|
||||
*/
|
||||
private HashMap<String, Boolean> parseFeature(String optString) {
|
||||
if (optString.equals(NULL)) {
|
||||
return null;
|
||||
} else {
|
||||
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
|
||||
StringTokenizer features = new StringTokenizer(optString, ",");
|
||||
StringTokenizer option;
|
||||
while(features.hasMoreElements()) {
|
||||
option = new StringTokenizer(features.nextToken(), "=");
|
||||
if (option.hasMoreElements()) {
|
||||
String key = option.nextToken();
|
||||
if (key.equalsIgnoreCase(CLOSE_BUTTON_CAPTION)) {
|
||||
this.buttonLabel = option.nextToken();
|
||||
} else {
|
||||
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
|
||||
map.put(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a new browser with the specified URL.
|
||||
*
|
||||
* @param url The url to load.
|
||||
* @param usePhoneGap Load url in PhoneGap webview
|
||||
* @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);
|
||||
}
|
||||
this.cordova.getActivity().startActivity(intent);
|
||||
return "";
|
||||
} catch (android.content.ActivityNotFoundException e) {
|
||||
Log.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString());
|
||||
return e.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the dialog
|
||||
*/
|
||||
public void closeDialog() {
|
||||
final WebView childView = this.inAppWebView;
|
||||
// The JS protects against multiple calls, so this should happen only when
|
||||
// closeDialog() is called by other native code.
|
||||
if (childView == null) {
|
||||
return;
|
||||
}
|
||||
this.cordova.getActivity().runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
childView.loadUrl("about:blank");
|
||||
if (dialog != null) {
|
||||
dialog.dismiss();
|
||||
}
|
||||
}
|
||||
});
|
||||
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.
|
||||
*/
|
||||
private void goBack() {
|
||||
if (this.inAppWebView.canGoBack()) {
|
||||
this.inAppWebView.goBack();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a new browser with the specified URL.
|
||||
*
|
||||
* @param url The url to load.
|
||||
* @param jsonObject
|
||||
*/
|
||||
public String showWebPage(final String url, HashMap<String, Boolean> features) {
|
||||
// Determine if we should hide the location bar.
|
||||
showLocationBar = true;
|
||||
openWindowHidden = false;
|
||||
if (features != null) {
|
||||
Boolean show = features.get(LOCATION);
|
||||
if (show != null) {
|
||||
showLocationBar = show.booleanValue();
|
||||
}
|
||||
Boolean hidden = features.get(HIDDEN);
|
||||
if (hidden != null) {
|
||||
openWindowHidden = hidden.booleanValue();
|
||||
}
|
||||
Boolean cache = features.get(CLEAR_ALL_CACHE);
|
||||
if (cache != null) {
|
||||
clearAllCache = cache.booleanValue();
|
||||
} else {
|
||||
cache = features.get(CLEAR_SESSION_CACHE);
|
||||
if (cache != null) {
|
||||
clearSessionCache = cache.booleanValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
// Let's create the main dialog
|
||||
dialog = new Dialog(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.setOnDismissListener(new DialogInterface.OnDismissListener() {
|
||||
public void onDismiss(DialogInterface dialog) {
|
||||
closeDialog();
|
||||
}
|
||||
});
|
||||
|
||||
// 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(android.graphics.Color.LTGRAY);
|
||||
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(1);
|
||||
|
||||
// Back button
|
||||
Button back = new Button(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(2);
|
||||
/*
|
||||
back.setText("<");
|
||||
*/
|
||||
Resources activityRes = cordova.getActivity().getResources();
|
||||
int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
|
||||
Drawable backIcon = activityRes.getDrawable(backResId);
|
||||
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
|
||||
{
|
||||
back.setBackgroundDrawable(backIcon);
|
||||
}
|
||||
else
|
||||
{
|
||||
back.setBackground(backIcon);
|
||||
}
|
||||
back.setOnClickListener(new View.OnClickListener() {
|
||||
public void onClick(View v) {
|
||||
goBack();
|
||||
}
|
||||
});
|
||||
|
||||
// Forward button
|
||||
Button forward = new Button(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(3);
|
||||
//forward.setText(">");
|
||||
int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
|
||||
Drawable fwdIcon = activityRes.getDrawable(fwdResId);
|
||||
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
|
||||
{
|
||||
forward.setBackgroundDrawable(fwdIcon);
|
||||
}
|
||||
else
|
||||
{
|
||||
forward.setBackground(fwdIcon);
|
||||
}
|
||||
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(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;
|
||||
}
|
||||
});
|
||||
|
||||
// Close button
|
||||
Button close = new Button(cordova.getActivity());
|
||||
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
|
||||
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
|
||||
close.setLayoutParams(closeLayoutParams);
|
||||
forward.setContentDescription("Close Button");
|
||||
close.setId(5);
|
||||
//close.setText(buttonLabel);
|
||||
int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
|
||||
Drawable closeIcon = activityRes.getDrawable(closeResId);
|
||||
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
|
||||
{
|
||||
close.setBackgroundDrawable(closeIcon);
|
||||
}
|
||||
else
|
||||
{
|
||||
close.setBackground(closeIcon);
|
||||
}
|
||||
close.setOnClickListener(new View.OnClickListener() {
|
||||
public void onClick(View v) {
|
||||
closeDialog();
|
||||
}
|
||||
});
|
||||
|
||||
// WebView
|
||||
inAppWebView = new WebView(cordova.getActivity());
|
||||
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
|
||||
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
|
||||
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
|
||||
inAppWebView.setWebViewClient(client);
|
||||
WebSettings settings = inAppWebView.getSettings();
|
||||
settings.setJavaScriptEnabled(true);
|
||||
settings.setJavaScriptCanOpenWindowsAutomatically(true);
|
||||
settings.setBuiltInZoomControls(true);
|
||||
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
|
||||
|
||||
//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();
|
||||
}
|
||||
|
||||
inAppWebView.loadUrl(url);
|
||||
inAppWebView.setId(6);
|
||||
inAppWebView.getSettings().setLoadWithOverviewMode(true);
|
||||
inAppWebView.getSettings().setUseWideViewPort(true);
|
||||
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
|
||||
toolbar.addView(actionButtonContainer);
|
||||
toolbar.addView(edittext);
|
||||
toolbar.addView(close);
|
||||
|
||||
// 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
|
||||
main.addView(inAppWebView);
|
||||
|
||||
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 "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The webview client receives notifications about appView
|
||||
*/
|
||||
public class InAppBrowserClient extends WebViewClient {
|
||||
EditText edittext;
|
||||
CordovaWebView webView;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param mContext
|
||||
* @param edittext
|
||||
*/
|
||||
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
|
||||
this.webView = webView;
|
||||
this.edittext = mEditText;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the host application that a page has started loading.
|
||||
*
|
||||
* @param view The webview initiating the callback.
|
||||
* @param url The url of the page.
|
||||
*/
|
||||
@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;
|
||||
}
|
||||
// If dialing phone (tel:5551212)
|
||||
else if (url.startsWith(WebView.SCHEME_TEL)) {
|
||||
try {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:")) {
|
||||
try {
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setData(Uri.parse(url));
|
||||
cordova.getActivity().startActivity(intent);
|
||||
} 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);
|
||||
} catch (android.content.ActivityNotFoundException e) {
|
||||
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
|
||||
}
|
||||
}
|
||||
else {
|
||||
newloc = "http://" + url;
|
||||
}
|
||||
|
||||
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.d(LOG_TAG, "Should never happen");
|
||||
}
|
||||
}
|
||||
|
||||
public void onPageFinished(WebView view, String url) {
|
||||
super.onPageFinished(view, url);
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package org.apache.cordova.inappbrowser;
|
||||
|
||||
import org.apache.cordova.CordovaWebView;
|
||||
import org.apache.cordova.LOG;
|
||||
import org.apache.cordova.PluginResult;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
|
||||
import android.webkit.JsPromptResult;
|
||||
import android.webkit.WebChromeClient;
|
||||
import android.webkit.WebStorage;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
import android.webkit.GeolocationPermissions.Callback;
|
||||
|
||||
public class InAppChromeClient extends WebChromeClient {
|
||||
|
||||
private CordovaWebView webView;
|
||||
private String LOG_TAG = "InAppChromeClient";
|
||||
private long MAX_QUOTA = 100 * 1024 * 1024;
|
||||
|
||||
public InAppChromeClient(CordovaWebView webView) {
|
||||
super();
|
||||
this.webView = webView;
|
||||
}
|
||||
/**
|
||||
* Handle database quota exceeded notification.
|
||||
*
|
||||
* @param url
|
||||
* @param databaseIdentifier
|
||||
* @param currentQuota
|
||||
* @param estimatedSize
|
||||
* @param totalUsedQuota
|
||||
* @param quotaUpdater
|
||||
*/
|
||||
@Override
|
||||
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
|
||||
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
|
||||
{
|
||||
LOG.d(LOG_TAG, "onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
|
||||
quotaUpdater.updateQuota(MAX_QUOTA);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.
|
||||
*
|
||||
* @param origin
|
||||
* @param callback
|
||||
*/
|
||||
@Override
|
||||
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
|
||||
super.onGeolocationPermissionsShowPrompt(origin, callback);
|
||||
callback.invoke(origin, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell the client to display a prompt dialog to the user.
|
||||
* If the client returns true, WebView will assume that the client will
|
||||
* handle the prompt dialog and call the appropriate JsPromptResult method.
|
||||
*
|
||||
* The prompt bridge provided for the InAppBrowser is capable of executing any
|
||||
* oustanding callback belonging to the InAppBrowser plugin. Care has been
|
||||
* taken that other callbacks cannot be triggered, and that no other code
|
||||
* execution is possible.
|
||||
*
|
||||
* To trigger the bridge, the prompt default value should be of the form:
|
||||
*
|
||||
* gap-iab://<callbackId>
|
||||
*
|
||||
* where <callbackId> is the string id of the callback to trigger (something
|
||||
* like "InAppBrowser0123456789")
|
||||
*
|
||||
* If present, the prompt message is expected to be a JSON-encoded value to
|
||||
* pass to the callback. A JSON_EXCEPTION is returned if the JSON is invalid.
|
||||
*
|
||||
* @param view
|
||||
* @param url
|
||||
* @param message
|
||||
* @param defaultValue
|
||||
* @param result
|
||||
*/
|
||||
@Override
|
||||
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
|
||||
// See if the prompt string uses the 'gap-iab' protocol. If so, the remainder should be the id of a callback to execute.
|
||||
if (defaultValue != null && defaultValue.startsWith("gap")) {
|
||||
if(defaultValue.startsWith("gap-iab://")) {
|
||||
PluginResult scriptResult;
|
||||
String scriptCallbackId = defaultValue.substring(10);
|
||||
if (scriptCallbackId.startsWith("InAppBrowser")) {
|
||||
if(message == null || message.length() == 0) {
|
||||
scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray());
|
||||
} else {
|
||||
try {
|
||||
scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray(message));
|
||||
} catch(JSONException e) {
|
||||
scriptResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
|
||||
}
|
||||
}
|
||||
this.webView.sendPluginResult(scriptResult, scriptCallbackId);
|
||||
result.confirm("");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Anything else with a gap: prefix should get this message
|
||||
LOG.w(LOG_TAG, "InAppBrowser does not support Cordova API calls: " + url + " " + defaultValue);
|
||||
result.cancel();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
After Width: | Height: | Size: 593 B |
|
After Width: | Height: | Size: 599 B |
|
After Width: | Height: | Size: 438 B |
|
After Width: | Height: | Size: 427 B |
|
After Width: | Height: | Size: 438 B |
|
After Width: | Height: | Size: 328 B |
|
After Width: | Height: | Size: 727 B |
|
After Width: | Height: | Size: 744 B |
|
After Width: | Height: | Size: 536 B |
|
After Width: | Height: | Size: 1021 B |
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 681 B |
@@ -0,0 +1,25 @@
|
||||
# BlackBerry 10 In-App-Browser Plugin
|
||||
|
||||
The in app browser functionality is entirely contained within common js. There is no native implementation required.
|
||||
To install this plugin, follow the [Command-line Interface Guide](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface).
|
||||
|
||||
If you are not using the Cordova Command-line Interface, follow [Using Plugman to Manage Plugins](http://cordova.apache.org/docs/en/edge/guide_plugin_ref_plugman.md.html).
|
||||
./cordova-plugin-battery-status/README.md
|
||||
./cordova-plugin-camera/README.md
|
||||
./cordova-plugin-console/README.md
|
||||
./cordova-plugin-contacts/README.md
|
||||
./cordova-plugin-device/README.md
|
||||
./cordova-plugin-device-motion/README.md
|
||||
./cordova-plugin-device-orientation/README.md
|
||||
./cordova-plugin-device-orientation/src/blackberry10/README.md
|
||||
./cordova-plugin-file/README.md
|
||||
./cordova-plugin-file-transfer/README.md
|
||||
./cordova-plugin-geolocation/README.md
|
||||
./cordova-plugin-globalization/README.md
|
||||
./cordova-plugin-inappbrowser/README.md
|
||||
./cordova-plugin-inappbrowser/src/blackberry10/README.md
|
||||
./cordova-plugin-media/README.md
|
||||
./cordova-plugin-media-capture/README.md
|
||||
./cordova-plugin-network-information/README.md
|
||||
./cordova-plugin-splashscreen/README.md
|
||||
./cordova-plugin-vibration/README.md
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
#import <Cordova/CDVPlugin.h>
|
||||
#import <Cordova/CDVInvokedUrlCommand.h>
|
||||
#import <Cordova/CDVScreenOrientationDelegate.h>
|
||||
#import <Cordova/CDVWebViewDelegate.h>
|
||||
|
||||
@class CDVInAppBrowserViewController;
|
||||
|
||||
@interface CDVInAppBrowser : CDVPlugin {
|
||||
BOOL _injectedIframeBridge;
|
||||
}
|
||||
|
||||
@property (nonatomic, retain) CDVInAppBrowserViewController* inAppBrowserViewController;
|
||||
@property (nonatomic, copy) NSString* callbackId;
|
||||
|
||||
- (void)open:(CDVInvokedUrlCommand*)command;
|
||||
- (void)close:(CDVInvokedUrlCommand*)command;
|
||||
- (void)injectScriptCode:(CDVInvokedUrlCommand*)command;
|
||||
- (void)show:(CDVInvokedUrlCommand*)command;
|
||||
|
||||
@end
|
||||
|
||||
@interface CDVInAppBrowserOptions : NSObject {}
|
||||
|
||||
@property (nonatomic, assign) BOOL location;
|
||||
@property (nonatomic, assign) BOOL toolbar;
|
||||
@property (nonatomic, copy) NSString* closebuttoncaption;
|
||||
@property (nonatomic, copy) NSString* toolbarposition;
|
||||
|
||||
@property (nonatomic, copy) NSString* presentationstyle;
|
||||
@property (nonatomic, copy) NSString* transitionstyle;
|
||||
|
||||
@property (nonatomic, assign) BOOL enableviewportscale;
|
||||
@property (nonatomic, assign) BOOL mediaplaybackrequiresuseraction;
|
||||
@property (nonatomic, assign) BOOL allowinlinemediaplayback;
|
||||
@property (nonatomic, assign) BOOL keyboarddisplayrequiresuseraction;
|
||||
@property (nonatomic, assign) BOOL suppressesincrementalrendering;
|
||||
@property (nonatomic, assign) BOOL hidden;
|
||||
@property (nonatomic, assign) BOOL disallowoverscroll;
|
||||
|
||||
+ (CDVInAppBrowserOptions*)parseOptions:(NSString*)options;
|
||||
|
||||
@end
|
||||
|
||||
@interface CDVInAppBrowserViewController : UIViewController <UIWebViewDelegate>{
|
||||
@private
|
||||
NSString* _userAgent;
|
||||
NSString* _prevUserAgent;
|
||||
NSInteger _userAgentLockToken;
|
||||
CDVInAppBrowserOptions *_browserOptions;
|
||||
CDVWebViewDelegate* _webViewDelegate;
|
||||
}
|
||||
|
||||
@property (nonatomic, strong) IBOutlet UIWebView* webView;
|
||||
@property (nonatomic, strong) IBOutlet UIBarButtonItem* closeButton;
|
||||
@property (nonatomic, strong) IBOutlet UILabel* addressLabel;
|
||||
@property (nonatomic, strong) IBOutlet UIBarButtonItem* backButton;
|
||||
@property (nonatomic, strong) IBOutlet UIBarButtonItem* forwardButton;
|
||||
@property (nonatomic, strong) IBOutlet UIActivityIndicatorView* spinner;
|
||||
@property (nonatomic, strong) IBOutlet UIToolbar* toolbar;
|
||||
|
||||
@property (nonatomic, weak) id <CDVScreenOrientationDelegate> orientationDelegate;
|
||||
@property (nonatomic, weak) CDVInAppBrowser* navigationDelegate;
|
||||
@property (nonatomic) NSURL* currentURL;
|
||||
|
||||
- (void)close;
|
||||
- (void)navigateTo:(NSURL*)url;
|
||||
- (void)showLocationBar:(BOOL)show;
|
||||
- (void)showToolBar:(BOOL)show : (NSString *) toolbarPosition;
|
||||
- (void)setCloseButtonTitle:(NSString*)title;
|
||||
|
||||
- (id)initWithUserAgent:(NSString*)userAgent prevUserAgent:(NSString*)prevUserAgent browserOptions: (CDVInAppBrowserOptions*) browserOptions;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,920 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
#import "CDVInAppBrowser.h"
|
||||
#import <Cordova/CDVPluginResult.h>
|
||||
#import <Cordova/CDVUserAgentUtil.h>
|
||||
#import <Cordova/CDVJSON.h>
|
||||
|
||||
#define kInAppBrowserTargetSelf @"_self"
|
||||
#define kInAppBrowserTargetSystem @"_system"
|
||||
#define kInAppBrowserTargetBlank @"_blank"
|
||||
|
||||
#define kInAppBrowserToolbarBarPositionBottom @"bottom"
|
||||
#define kInAppBrowserToolbarBarPositionTop @"top"
|
||||
|
||||
#define TOOLBAR_HEIGHT 44.0
|
||||
#define LOCATIONBAR_HEIGHT 21.0
|
||||
#define FOOTER_HEIGHT ((TOOLBAR_HEIGHT) + (LOCATIONBAR_HEIGHT))
|
||||
|
||||
#pragma mark CDVInAppBrowser
|
||||
|
||||
@interface CDVInAppBrowser () {
|
||||
NSInteger _previousStatusBarStyle;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation CDVInAppBrowser
|
||||
|
||||
- (CDVInAppBrowser*)initWithWebView:(UIWebView*)theWebView
|
||||
{
|
||||
self = [super initWithWebView:theWebView];
|
||||
if (self != nil) {
|
||||
_previousStatusBarStyle = -1;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)onReset
|
||||
{
|
||||
[self close:nil];
|
||||
}
|
||||
|
||||
- (void)close:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
if (self.inAppBrowserViewController == nil) {
|
||||
NSLog(@"IAB.close() called but it was already closed.");
|
||||
return;
|
||||
}
|
||||
// Things are cleaned up in browserExit.
|
||||
[self.inAppBrowserViewController close];
|
||||
}
|
||||
|
||||
- (BOOL) isSystemUrl:(NSURL*)url
|
||||
{
|
||||
if ([[url host] isEqualToString:@"itunes.apple.com"]) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)open:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
CDVPluginResult* pluginResult;
|
||||
|
||||
NSString* url = [command argumentAtIndex:0];
|
||||
NSString* target = [command argumentAtIndex:1 withDefault:kInAppBrowserTargetSelf];
|
||||
NSString* options = [command argumentAtIndex:2 withDefault:@"" andClass:[NSString class]];
|
||||
|
||||
self.callbackId = command.callbackId;
|
||||
|
||||
if (url != nil) {
|
||||
NSURL* baseUrl = [self.webView.request URL];
|
||||
NSURL* absoluteUrl = [[NSURL URLWithString:url relativeToURL:baseUrl] absoluteURL];
|
||||
|
||||
if ([self isSystemUrl:absoluteUrl]) {
|
||||
target = kInAppBrowserTargetSystem;
|
||||
}
|
||||
|
||||
if ([target isEqualToString:kInAppBrowserTargetSelf]) {
|
||||
[self openInCordovaWebView:absoluteUrl withOptions:options];
|
||||
} else if ([target isEqualToString:kInAppBrowserTargetSystem]) {
|
||||
[self openInSystem:absoluteUrl];
|
||||
} else { // _blank or anything else
|
||||
[self openInInAppBrowser:absoluteUrl withOptions:options];
|
||||
}
|
||||
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
|
||||
} else {
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"incorrect number of arguments"];
|
||||
}
|
||||
|
||||
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
|
||||
}
|
||||
|
||||
- (void)openInInAppBrowser:(NSURL*)url withOptions:(NSString*)options
|
||||
{
|
||||
CDVInAppBrowserOptions* browserOptions = [CDVInAppBrowserOptions parseOptions:options];
|
||||
if (self.inAppBrowserViewController == nil) {
|
||||
NSString* originalUA = [CDVUserAgentUtil originalUserAgent];
|
||||
self.inAppBrowserViewController = [[CDVInAppBrowserViewController alloc] initWithUserAgent:originalUA prevUserAgent:[self.commandDelegate userAgent] browserOptions: browserOptions];
|
||||
self.inAppBrowserViewController.navigationDelegate = self;
|
||||
|
||||
if ([self.viewController conformsToProtocol:@protocol(CDVScreenOrientationDelegate)]) {
|
||||
self.inAppBrowserViewController.orientationDelegate = (UIViewController <CDVScreenOrientationDelegate>*)self.viewController;
|
||||
}
|
||||
}
|
||||
|
||||
[self.inAppBrowserViewController showLocationBar:browserOptions.location];
|
||||
[self.inAppBrowserViewController showToolBar:browserOptions.toolbar :browserOptions.toolbarposition];
|
||||
if (browserOptions.closebuttoncaption != nil) {
|
||||
[self.inAppBrowserViewController setCloseButtonTitle:browserOptions.closebuttoncaption];
|
||||
}
|
||||
// Set Presentation Style
|
||||
UIModalPresentationStyle presentationStyle = UIModalPresentationFullScreen; // default
|
||||
if (browserOptions.presentationstyle != nil) {
|
||||
if ([[browserOptions.presentationstyle lowercaseString] isEqualToString:@"pagesheet"]) {
|
||||
presentationStyle = UIModalPresentationPageSheet;
|
||||
} else if ([[browserOptions.presentationstyle lowercaseString] isEqualToString:@"formsheet"]) {
|
||||
presentationStyle = UIModalPresentationFormSheet;
|
||||
}
|
||||
}
|
||||
self.inAppBrowserViewController.modalPresentationStyle = presentationStyle;
|
||||
|
||||
// Set Transition Style
|
||||
UIModalTransitionStyle transitionStyle = UIModalTransitionStyleCoverVertical; // default
|
||||
if (browserOptions.transitionstyle != nil) {
|
||||
if ([[browserOptions.transitionstyle lowercaseString] isEqualToString:@"fliphorizontal"]) {
|
||||
transitionStyle = UIModalTransitionStyleFlipHorizontal;
|
||||
} else if ([[browserOptions.transitionstyle lowercaseString] isEqualToString:@"crossdissolve"]) {
|
||||
transitionStyle = UIModalTransitionStyleCrossDissolve;
|
||||
}
|
||||
}
|
||||
self.inAppBrowserViewController.modalTransitionStyle = transitionStyle;
|
||||
|
||||
// prevent webView from bouncing
|
||||
if (browserOptions.disallowoverscroll) {
|
||||
if ([self.inAppBrowserViewController.webView respondsToSelector:@selector(scrollView)]) {
|
||||
((UIScrollView*)[self.inAppBrowserViewController.webView scrollView]).bounces = NO;
|
||||
} else {
|
||||
for (id subview in self.inAppBrowserViewController.webView.subviews) {
|
||||
if ([[subview class] isSubclassOfClass:[UIScrollView class]]) {
|
||||
((UIScrollView*)subview).bounces = NO;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UIWebView options
|
||||
self.inAppBrowserViewController.webView.scalesPageToFit = browserOptions.enableviewportscale;
|
||||
self.inAppBrowserViewController.webView.mediaPlaybackRequiresUserAction = browserOptions.mediaplaybackrequiresuseraction;
|
||||
self.inAppBrowserViewController.webView.allowsInlineMediaPlayback = browserOptions.allowinlinemediaplayback;
|
||||
if (IsAtLeastiOSVersion(@"6.0")) {
|
||||
self.inAppBrowserViewController.webView.keyboardDisplayRequiresUserAction = browserOptions.keyboarddisplayrequiresuseraction;
|
||||
self.inAppBrowserViewController.webView.suppressesIncrementalRendering = browserOptions.suppressesincrementalrendering;
|
||||
}
|
||||
|
||||
[self.inAppBrowserViewController navigateTo:url];
|
||||
if (!browserOptions.hidden) {
|
||||
[self show:nil];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)show:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
if (self.inAppBrowserViewController == nil) {
|
||||
NSLog(@"Tried to show IAB after it was closed.");
|
||||
return;
|
||||
}
|
||||
if (_previousStatusBarStyle != -1) {
|
||||
NSLog(@"Tried to show IAB while already shown");
|
||||
return;
|
||||
}
|
||||
|
||||
_previousStatusBarStyle = [UIApplication sharedApplication].statusBarStyle;
|
||||
|
||||
UINavigationController* nav = [[UINavigationController alloc]
|
||||
initWithRootViewController:self.inAppBrowserViewController];
|
||||
nav.navigationBarHidden = YES;
|
||||
// Run later to avoid the "took a long time" log message.
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (self.inAppBrowserViewController != nil) {
|
||||
[self.viewController presentModalViewController:nav animated:YES];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)openInCordovaWebView:(NSURL*)url withOptions:(NSString*)options
|
||||
{
|
||||
if ([self.commandDelegate URLIsWhitelisted:url]) {
|
||||
NSURLRequest* request = [NSURLRequest requestWithURL:url];
|
||||
[self.webView loadRequest:request];
|
||||
} else { // this assumes the InAppBrowser can be excepted from the white-list
|
||||
[self openInInAppBrowser:url withOptions:options];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)openInSystem:(NSURL*)url
|
||||
{
|
||||
if ([[UIApplication sharedApplication] canOpenURL:url]) {
|
||||
[[UIApplication sharedApplication] openURL:url];
|
||||
} else { // handle any custom schemes to plugins
|
||||
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
// '%@' marker).
|
||||
//
|
||||
// If no wrapper is supplied, then the source string is executed directly.
|
||||
|
||||
- (void)injectDeferredObject:(NSString*)source withWrapper:(NSString*)jsWrapper
|
||||
{
|
||||
if (!_injectedIframeBridge) {
|
||||
_injectedIframeBridge = YES;
|
||||
// Create an iframe bridge in the new document to communicate with the CDVInAppBrowserViewController
|
||||
[self.inAppBrowserViewController.webView stringByEvaluatingJavaScriptFromString:@"(function(d){var e = _cdvIframeBridge = d.createElement('iframe');e.style.display='none';d.body.appendChild(e);})(document)"];
|
||||
}
|
||||
|
||||
if (jsWrapper != nil) {
|
||||
NSString* sourceArrayString = [@[source] JSONString];
|
||||
if (sourceArrayString) {
|
||||
NSString* sourceString = [sourceArrayString substringWithRange:NSMakeRange(1, [sourceArrayString length] - 2)];
|
||||
NSString* jsToInject = [NSString stringWithFormat:jsWrapper, sourceString];
|
||||
[self.inAppBrowserViewController.webView stringByEvaluatingJavaScriptFromString:jsToInject];
|
||||
}
|
||||
} else {
|
||||
[self.inAppBrowserViewController.webView stringByEvaluatingJavaScriptFromString:source];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)injectScriptCode:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
NSString* jsWrapper = nil;
|
||||
|
||||
if ((command.callbackId != nil) && ![command.callbackId isEqualToString:@"INVALID"]) {
|
||||
jsWrapper = [NSString stringWithFormat:@"_cdvIframeBridge.src='gap-iab://%@/'+encodeURIComponent(JSON.stringify([eval(%%@)]));", command.callbackId];
|
||||
}
|
||||
[self injectDeferredObject:[command argumentAtIndex:0] withWrapper:jsWrapper];
|
||||
}
|
||||
|
||||
- (void)injectScriptFile:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
NSString* jsWrapper;
|
||||
|
||||
if ((command.callbackId != nil) && ![command.callbackId isEqualToString:@"INVALID"]) {
|
||||
jsWrapper = [NSString stringWithFormat:@"(function(d) { var c = d.createElement('script'); c.src = %%@; c.onload = function() { _cdvIframeBridge.src='gap-iab://%@'; }; d.body.appendChild(c); })(document)", command.callbackId];
|
||||
} else {
|
||||
jsWrapper = @"(function(d) { var c = d.createElement('script'); c.src = %@; d.body.appendChild(c); })(document)";
|
||||
}
|
||||
[self injectDeferredObject:[command argumentAtIndex:0] withWrapper:jsWrapper];
|
||||
}
|
||||
|
||||
- (void)injectStyleCode:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
NSString* jsWrapper;
|
||||
|
||||
if ((command.callbackId != nil) && ![command.callbackId isEqualToString:@"INVALID"]) {
|
||||
jsWrapper = [NSString stringWithFormat:@"(function(d) { var c = d.createElement('style'); c.innerHTML = %%@; c.onload = function() { _cdvIframeBridge.src='gap-iab://%@'; }; d.body.appendChild(c); })(document)", command.callbackId];
|
||||
} else {
|
||||
jsWrapper = @"(function(d) { var c = d.createElement('style'); c.innerHTML = %@; d.body.appendChild(c); })(document)";
|
||||
}
|
||||
[self injectDeferredObject:[command argumentAtIndex:0] withWrapper:jsWrapper];
|
||||
}
|
||||
|
||||
- (void)injectStyleFile:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
NSString* jsWrapper;
|
||||
|
||||
if ((command.callbackId != nil) && ![command.callbackId isEqualToString:@"INVALID"]) {
|
||||
jsWrapper = [NSString stringWithFormat:@"(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%@; c.onload = function() { _cdvIframeBridge.src='gap-iab://%@'; }; d.body.appendChild(c); })(document)", command.callbackId];
|
||||
} else {
|
||||
jsWrapper = @"(function(d) { var c = d.createElement('link'); c.rel='stylesheet', c.type='text/css'; c.href = %@; d.body.appendChild(c); })(document)";
|
||||
}
|
||||
[self injectDeferredObject:[command argumentAtIndex:0] withWrapper:jsWrapper];
|
||||
}
|
||||
|
||||
/**
|
||||
* The iframe bridge provided for the InAppBrowser is capable of executing any oustanding callback belonging
|
||||
* to the InAppBrowser plugin. Care has been taken that other callbacks cannot be triggered, and that no
|
||||
* other code execution is possible.
|
||||
*
|
||||
* To trigger the bridge, the iframe (or any other resource) should attempt to load a url of the form:
|
||||
*
|
||||
* gap-iab://<callbackId>/<arguments>
|
||||
*
|
||||
* where <callbackId> is the string id of the callback to trigger (something like "InAppBrowser0123456789")
|
||||
*
|
||||
* If present, the path component of the special gap-iab:// url is expected to be a URL-escaped JSON-encoded
|
||||
* value to pass to the callback. [NSURL path] should take care of the URL-unescaping, and a JSON_EXCEPTION
|
||||
* is returned if the JSON is invalid.
|
||||
*/
|
||||
- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
|
||||
{
|
||||
NSURL* url = request.URL;
|
||||
BOOL isTopLevelNavigation = [request.URL isEqual:[request mainDocumentURL]];
|
||||
|
||||
// See if the url uses the 'gap-iab' protocol. If so, the host should be the id of a callback to execute,
|
||||
// and the path, if present, should be a JSON-encoded value to pass to the callback.
|
||||
if ([[url scheme] isEqualToString:@"gap-iab"]) {
|
||||
NSString* scriptCallbackId = [url host];
|
||||
CDVPluginResult* pluginResult = nil;
|
||||
|
||||
if ([scriptCallbackId hasPrefix:@"InAppBrowser"]) {
|
||||
NSString* scriptResult = [url path];
|
||||
NSError* __autoreleasing error = nil;
|
||||
|
||||
// The message should be a JSON-encoded array of the result of the script which executed.
|
||||
if ((scriptResult != nil) && ([scriptResult length] > 1)) {
|
||||
scriptResult = [scriptResult substringFromIndex:1];
|
||||
NSData* decodedResult = [NSJSONSerialization JSONObjectWithData:[scriptResult dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
|
||||
if ((error == nil) && [decodedResult isKindOfClass:[NSArray class]]) {
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:(NSArray*)decodedResult];
|
||||
} else {
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_JSON_EXCEPTION];
|
||||
}
|
||||
} else {
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:@[]];
|
||||
}
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:scriptCallbackId];
|
||||
return NO;
|
||||
}
|
||||
} else if ((self.callbackId != nil) && isTopLevelNavigation) {
|
||||
// Send a loadstart event for each top-level navigation (includes redirects).
|
||||
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
|
||||
messageAsDictionary:@{@"type":@"loadstart", @"url":[url absoluteString]}];
|
||||
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
|
||||
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)webViewDidStartLoad:(UIWebView*)theWebView
|
||||
{
|
||||
_injectedIframeBridge = NO;
|
||||
}
|
||||
|
||||
- (void)webViewDidFinishLoad:(UIWebView*)theWebView
|
||||
{
|
||||
if (self.callbackId != nil) {
|
||||
// TODO: It would be more useful to return the URL the page is actually on (e.g. if it's been redirected).
|
||||
NSString* url = [self.inAppBrowserViewController.currentURL absoluteString];
|
||||
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
|
||||
messageAsDictionary:@{@"type":@"loadstop", @"url":url}];
|
||||
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
|
||||
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error
|
||||
{
|
||||
if (self.callbackId != nil) {
|
||||
NSString* url = [self.inAppBrowserViewController.currentURL absoluteString];
|
||||
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
|
||||
messageAsDictionary:@{@"type":@"loaderror", @"url":url, @"code": [NSNumber numberWithInt:error.code], @"message": error.localizedDescription}];
|
||||
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
|
||||
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)browserExit
|
||||
{
|
||||
if (self.callbackId != nil) {
|
||||
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
|
||||
messageAsDictionary:@{@"type":@"exit"}];
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
|
||||
self.callbackId = nil;
|
||||
}
|
||||
// Set navigationDelegate to nil to ensure no callbacks are received from it.
|
||||
self.inAppBrowserViewController.navigationDelegate = nil;
|
||||
// Don't recycle the ViewController since it may be consuming a lot of memory.
|
||||
// Also - this is required for the PDF/User-Agent bug work-around.
|
||||
self.inAppBrowserViewController = nil;
|
||||
|
||||
_previousStatusBarStyle = -1;
|
||||
|
||||
if (IsAtLeastiOSVersion(@"7.0")) {
|
||||
[[UIApplication sharedApplication] setStatusBarStyle:_previousStatusBarStyle];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark CDVInAppBrowserViewController
|
||||
|
||||
@implementation CDVInAppBrowserViewController
|
||||
|
||||
@synthesize currentURL;
|
||||
|
||||
- (id)initWithUserAgent:(NSString*)userAgent prevUserAgent:(NSString*)prevUserAgent browserOptions: (CDVInAppBrowserOptions*) browserOptions
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_userAgent = userAgent;
|
||||
_prevUserAgent = prevUserAgent;
|
||||
_browserOptions = browserOptions;
|
||||
_webViewDelegate = [[CDVWebViewDelegate alloc] initWithDelegate:self];
|
||||
[self createViews];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)createViews
|
||||
{
|
||||
// We create the views in code for primarily for ease of upgrades and not requiring an external .xib to be included
|
||||
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
BOOL toolbarIsAtBottom = ![_browserOptions.toolbarposition isEqualToString:kInAppBrowserToolbarBarPositionTop];
|
||||
webViewBounds.size.height -= _browserOptions.location ? FOOTER_HEIGHT : TOOLBAR_HEIGHT;
|
||||
self.webView = [[UIWebView alloc] initWithFrame:webViewBounds];
|
||||
|
||||
self.webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
|
||||
|
||||
[self.view addSubview:self.webView];
|
||||
[self.view sendSubviewToBack:self.webView];
|
||||
|
||||
self.webView.delegate = _webViewDelegate;
|
||||
self.webView.backgroundColor = [UIColor whiteColor];
|
||||
|
||||
self.webView.clearsContextBeforeDrawing = YES;
|
||||
self.webView.clipsToBounds = YES;
|
||||
self.webView.contentMode = UIViewContentModeScaleToFill;
|
||||
self.webView.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
|
||||
self.webView.multipleTouchEnabled = YES;
|
||||
self.webView.opaque = YES;
|
||||
self.webView.scalesPageToFit = NO;
|
||||
self.webView.userInteractionEnabled = YES;
|
||||
|
||||
self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
|
||||
self.spinner.alpha = 1.000;
|
||||
self.spinner.autoresizesSubviews = YES;
|
||||
self.spinner.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
|
||||
self.spinner.clearsContextBeforeDrawing = NO;
|
||||
self.spinner.clipsToBounds = NO;
|
||||
self.spinner.contentMode = UIViewContentModeScaleToFill;
|
||||
self.spinner.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
|
||||
self.spinner.frame = CGRectMake(454.0, 231.0, 20.0, 20.0);
|
||||
self.spinner.hidden = YES;
|
||||
self.spinner.hidesWhenStopped = YES;
|
||||
self.spinner.multipleTouchEnabled = NO;
|
||||
self.spinner.opaque = NO;
|
||||
self.spinner.userInteractionEnabled = NO;
|
||||
[self.spinner stopAnimating];
|
||||
|
||||
self.closeButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(close)];
|
||||
self.closeButton.enabled = YES;
|
||||
|
||||
UIBarButtonItem* flexibleSpaceButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
|
||||
|
||||
UIBarButtonItem* fixedSpaceButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
|
||||
fixedSpaceButton.width = 20;
|
||||
|
||||
float toolbarY = toolbarIsAtBottom ? self.view.bounds.size.height - TOOLBAR_HEIGHT : 0.0;
|
||||
CGRect toolbarFrame = CGRectMake(0.0, toolbarY, self.view.bounds.size.width, TOOLBAR_HEIGHT);
|
||||
|
||||
self.toolbar = [[UIToolbar alloc] initWithFrame:toolbarFrame];
|
||||
self.toolbar.alpha = 1.000;
|
||||
self.toolbar.autoresizesSubviews = YES;
|
||||
self.toolbar.autoresizingMask = toolbarIsAtBottom ? (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin) : UIViewAutoresizingFlexibleWidth;
|
||||
self.toolbar.barStyle = UIBarStyleBlackOpaque;
|
||||
self.toolbar.clearsContextBeforeDrawing = NO;
|
||||
self.toolbar.clipsToBounds = NO;
|
||||
self.toolbar.contentMode = UIViewContentModeScaleToFill;
|
||||
self.toolbar.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
|
||||
self.toolbar.hidden = NO;
|
||||
self.toolbar.multipleTouchEnabled = NO;
|
||||
self.toolbar.opaque = NO;
|
||||
self.toolbar.userInteractionEnabled = YES;
|
||||
|
||||
CGFloat labelInset = 5.0;
|
||||
float locationBarY = toolbarIsAtBottom ? self.view.bounds.size.height - FOOTER_HEIGHT : self.view.bounds.size.height - LOCATIONBAR_HEIGHT;
|
||||
|
||||
self.addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(labelInset, locationBarY, self.view.bounds.size.width - labelInset, LOCATIONBAR_HEIGHT)];
|
||||
self.addressLabel.adjustsFontSizeToFitWidth = NO;
|
||||
self.addressLabel.alpha = 1.000;
|
||||
self.addressLabel.autoresizesSubviews = YES;
|
||||
self.addressLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
|
||||
self.addressLabel.backgroundColor = [UIColor clearColor];
|
||||
self.addressLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
|
||||
self.addressLabel.clearsContextBeforeDrawing = YES;
|
||||
self.addressLabel.clipsToBounds = YES;
|
||||
self.addressLabel.contentMode = UIViewContentModeScaleToFill;
|
||||
self.addressLabel.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
|
||||
self.addressLabel.enabled = YES;
|
||||
self.addressLabel.hidden = NO;
|
||||
self.addressLabel.lineBreakMode = UILineBreakModeTailTruncation;
|
||||
self.addressLabel.minimumFontSize = 10.000;
|
||||
self.addressLabel.multipleTouchEnabled = NO;
|
||||
self.addressLabel.numberOfLines = 1;
|
||||
self.addressLabel.opaque = NO;
|
||||
self.addressLabel.shadowOffset = CGSizeMake(0.0, -1.0);
|
||||
self.addressLabel.text = NSLocalizedString(@"Loading...", nil);
|
||||
self.addressLabel.textAlignment = UITextAlignmentLeft;
|
||||
self.addressLabel.textColor = [UIColor colorWithWhite:1.000 alpha:1.000];
|
||||
self.addressLabel.userInteractionEnabled = NO;
|
||||
|
||||
NSString* frontArrowString = NSLocalizedString(@"►", nil); // create arrow from Unicode char
|
||||
self.forwardButton = [[UIBarButtonItem alloc] initWithTitle:frontArrowString style:UIBarButtonItemStylePlain target:self action:@selector(goForward:)];
|
||||
self.forwardButton.enabled = YES;
|
||||
self.forwardButton.imageInsets = UIEdgeInsetsZero;
|
||||
|
||||
NSString* backArrowString = NSLocalizedString(@"◄", nil); // create arrow from Unicode char
|
||||
self.backButton = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStylePlain target:self action:@selector(goBack:)];
|
||||
self.backButton.enabled = YES;
|
||||
self.backButton.imageInsets = UIEdgeInsetsZero;
|
||||
|
||||
[self.toolbar setItems:@[self.closeButton, flexibleSpaceButton, self.backButton, fixedSpaceButton, self.forwardButton]];
|
||||
|
||||
self.view.backgroundColor = [UIColor grayColor];
|
||||
[self.view addSubview:self.toolbar];
|
||||
[self.view addSubview:self.addressLabel];
|
||||
[self.view addSubview:self.spinner];
|
||||
}
|
||||
|
||||
- (void) setWebViewFrame : (CGRect) frame {
|
||||
NSLog(@"Setting the WebView's frame to %@", NSStringFromCGRect(frame));
|
||||
[self.webView setFrame:frame];
|
||||
}
|
||||
|
||||
- (void)setCloseButtonTitle:(NSString*)title
|
||||
{
|
||||
// the advantage of using UIBarButtonSystemItemDone is the system will localize it for you automatically
|
||||
// but, if you want to set this yourself, knock yourself out (we can't set the title for a system Done button, so we have to create a new one)
|
||||
self.closeButton = nil;
|
||||
self.closeButton = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStyleBordered target:self action:@selector(close)];
|
||||
self.closeButton.enabled = YES;
|
||||
self.closeButton.tintColor = [UIColor colorWithRed:60.0 / 255.0 green:136.0 / 255.0 blue:230.0 / 255.0 alpha:1];
|
||||
|
||||
NSMutableArray* items = [self.toolbar.items mutableCopy];
|
||||
[items replaceObjectAtIndex:0 withObject:self.closeButton];
|
||||
[self.toolbar setItems:items];
|
||||
}
|
||||
|
||||
- (void)showLocationBar:(BOOL)show
|
||||
{
|
||||
CGRect locationbarFrame = self.addressLabel.frame;
|
||||
|
||||
BOOL toolbarVisible = !self.toolbar.hidden;
|
||||
|
||||
// prevent double show/hide
|
||||
if (show == !(self.addressLabel.hidden)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (show) {
|
||||
self.addressLabel.hidden = NO;
|
||||
|
||||
if (toolbarVisible) {
|
||||
// toolBar at the bottom, leave as is
|
||||
// put locationBar on top of the toolBar
|
||||
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
webViewBounds.size.height -= FOOTER_HEIGHT;
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
|
||||
locationbarFrame.origin.y = webViewBounds.size.height;
|
||||
self.addressLabel.frame = locationbarFrame;
|
||||
} else {
|
||||
// no toolBar, so put locationBar at the bottom
|
||||
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
webViewBounds.size.height -= LOCATIONBAR_HEIGHT;
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
|
||||
locationbarFrame.origin.y = webViewBounds.size.height;
|
||||
self.addressLabel.frame = locationbarFrame;
|
||||
}
|
||||
} else {
|
||||
self.addressLabel.hidden = YES;
|
||||
|
||||
if (toolbarVisible) {
|
||||
// locationBar is on top of toolBar, hide locationBar
|
||||
|
||||
// webView take up whole height less toolBar height
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
webViewBounds.size.height -= TOOLBAR_HEIGHT;
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
} else {
|
||||
// no toolBar, expand webView to screen dimensions
|
||||
[self setWebViewFrame:self.view.bounds];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)showToolBar:(BOOL)show : (NSString *) toolbarPosition
|
||||
{
|
||||
CGRect toolbarFrame = self.toolbar.frame;
|
||||
CGRect locationbarFrame = self.addressLabel.frame;
|
||||
|
||||
BOOL locationbarVisible = !self.addressLabel.hidden;
|
||||
|
||||
// prevent double show/hide
|
||||
if (show == !(self.toolbar.hidden)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (show) {
|
||||
self.toolbar.hidden = NO;
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
|
||||
if (locationbarVisible) {
|
||||
// locationBar at the bottom, move locationBar up
|
||||
// put toolBar at the bottom
|
||||
webViewBounds.size.height -= FOOTER_HEIGHT;
|
||||
locationbarFrame.origin.y = webViewBounds.size.height;
|
||||
self.addressLabel.frame = locationbarFrame;
|
||||
self.toolbar.frame = toolbarFrame;
|
||||
} else {
|
||||
// no locationBar, so put toolBar at the bottom
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
webViewBounds.size.height -= TOOLBAR_HEIGHT;
|
||||
self.toolbar.frame = toolbarFrame;
|
||||
}
|
||||
|
||||
if ([toolbarPosition isEqualToString:kInAppBrowserToolbarBarPositionTop]) {
|
||||
toolbarFrame.origin.y = 0;
|
||||
webViewBounds.origin.y += toolbarFrame.size.height;
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
} else {
|
||||
toolbarFrame.origin.y = (webViewBounds.size.height + LOCATIONBAR_HEIGHT);
|
||||
}
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
|
||||
} else {
|
||||
self.toolbar.hidden = YES;
|
||||
|
||||
if (locationbarVisible) {
|
||||
// locationBar is on top of toolBar, hide toolBar
|
||||
// put locationBar at the bottom
|
||||
|
||||
// webView take up whole height less locationBar height
|
||||
CGRect webViewBounds = self.view.bounds;
|
||||
webViewBounds.size.height -= LOCATIONBAR_HEIGHT;
|
||||
[self setWebViewFrame:webViewBounds];
|
||||
|
||||
// move locationBar down
|
||||
locationbarFrame.origin.y = webViewBounds.size.height;
|
||||
self.addressLabel.frame = locationbarFrame;
|
||||
} else {
|
||||
// no locationBar, expand webView to screen dimensions
|
||||
[self setWebViewFrame:self.view.bounds];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)viewDidLoad
|
||||
{
|
||||
[super viewDidLoad];
|
||||
}
|
||||
|
||||
- (void)viewDidUnload
|
||||
{
|
||||
[self.webView loadHTMLString:nil baseURL:nil];
|
||||
[CDVUserAgentUtil releaseLock:&_userAgentLockToken];
|
||||
[super viewDidUnload];
|
||||
}
|
||||
|
||||
- (UIStatusBarStyle)preferredStatusBarStyle
|
||||
{
|
||||
return UIStatusBarStyleDefault;
|
||||
}
|
||||
|
||||
- (void)close
|
||||
{
|
||||
[CDVUserAgentUtil releaseLock:&_userAgentLockToken];
|
||||
self.currentURL = nil;
|
||||
|
||||
if ((self.navigationDelegate != nil) && [self.navigationDelegate respondsToSelector:@selector(browserExit)]) {
|
||||
[self.navigationDelegate browserExit];
|
||||
}
|
||||
|
||||
// Run later to avoid the "took a long time" log message.
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if ([self respondsToSelector:@selector(presentingViewController)]) {
|
||||
[[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
|
||||
} else {
|
||||
[[self parentViewController] dismissModalViewControllerAnimated:YES];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)navigateTo:(NSURL*)url
|
||||
{
|
||||
NSURLRequest* request = [NSURLRequest requestWithURL:url];
|
||||
|
||||
if (_userAgentLockToken != 0) {
|
||||
[self.webView loadRequest:request];
|
||||
} else {
|
||||
[CDVUserAgentUtil acquireLock:^(NSInteger lockToken) {
|
||||
_userAgentLockToken = lockToken;
|
||||
[CDVUserAgentUtil setUserAgent:_userAgent lockToken:lockToken];
|
||||
[self.webView loadRequest:request];
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)goBack:(id)sender
|
||||
{
|
||||
[self.webView goBack];
|
||||
}
|
||||
|
||||
- (void)goForward:(id)sender
|
||||
{
|
||||
[self.webView goForward];
|
||||
}
|
||||
|
||||
- (void)viewWillAppear:(BOOL)animated
|
||||
{
|
||||
if (IsAtLeastiOSVersion(@"7.0")) {
|
||||
[[UIApplication sharedApplication] setStatusBarStyle:[self preferredStatusBarStyle]];
|
||||
}
|
||||
[self rePositionViews];
|
||||
|
||||
[super viewWillAppear:animated];
|
||||
}
|
||||
|
||||
//
|
||||
// On iOS 7 the status bar is part of the view's dimensions, therefore it's height has to be taken into account.
|
||||
// The height of it could be hardcoded as 20 pixels, but that would assume that the upcoming releases of iOS won't
|
||||
// change that value.
|
||||
//
|
||||
- (float) getStatusBarOffset {
|
||||
CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
|
||||
float statusBarOffset = IsAtLeastiOSVersion(@"7.0") ? MIN(statusBarFrame.size.width, statusBarFrame.size.height) : 0.0;
|
||||
return statusBarOffset;
|
||||
}
|
||||
|
||||
- (void) rePositionViews {
|
||||
if ([_browserOptions.toolbarposition isEqualToString:kInAppBrowserToolbarBarPositionTop]) {
|
||||
[self.webView setFrame:CGRectMake(self.webView.frame.origin.x, TOOLBAR_HEIGHT, self.webView.frame.size.width, self.webView.frame.size.height)];
|
||||
[self.toolbar setFrame:CGRectMake(self.toolbar.frame.origin.x, [self getStatusBarOffset], self.toolbar.frame.size.width, self.toolbar.frame.size.height)];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark UIWebViewDelegate
|
||||
|
||||
- (void)webViewDidStartLoad:(UIWebView*)theWebView
|
||||
{
|
||||
// loading url, start spinner, update back/forward
|
||||
|
||||
self.addressLabel.text = NSLocalizedString(@"Loading...", nil);
|
||||
self.backButton.enabled = theWebView.canGoBack;
|
||||
self.forwardButton.enabled = theWebView.canGoForward;
|
||||
|
||||
[self.spinner startAnimating];
|
||||
|
||||
return [self.navigationDelegate webViewDidStartLoad:theWebView];
|
||||
}
|
||||
|
||||
- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
|
||||
{
|
||||
BOOL isTopLevelNavigation = [request.URL isEqual:[request mainDocumentURL]];
|
||||
|
||||
if (isTopLevelNavigation) {
|
||||
self.currentURL = request.URL;
|
||||
}
|
||||
return [self.navigationDelegate webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
|
||||
}
|
||||
|
||||
- (void)webViewDidFinishLoad:(UIWebView*)theWebView
|
||||
{
|
||||
// update url, stop spinner, update back/forward
|
||||
|
||||
self.addressLabel.text = [self.currentURL absoluteString];
|
||||
self.backButton.enabled = theWebView.canGoBack;
|
||||
self.forwardButton.enabled = theWebView.canGoForward;
|
||||
|
||||
[self.spinner stopAnimating];
|
||||
|
||||
// Work around a bug where the first time a PDF is opened, all UIWebViews
|
||||
// reload their User-Agent from NSUserDefaults.
|
||||
// This work-around makes the following assumptions:
|
||||
// 1. The app has only a single Cordova Webview. If not, then the app should
|
||||
// take it upon themselves to load a PDF in the background as a part of
|
||||
// their start-up flow.
|
||||
// 2. That the PDF does not require any additional network requests. We change
|
||||
// the user-agent here back to that of the CDVViewController, so requests
|
||||
// from it must pass through its white-list. This *does* break PDFs that
|
||||
// contain links to other remote PDF/websites.
|
||||
// More info at https://issues.apache.org/jira/browse/CB-2225
|
||||
BOOL isPDF = [@"true" isEqualToString :[theWebView stringByEvaluatingJavaScriptFromString:@"document.body==null"]];
|
||||
if (isPDF) {
|
||||
[CDVUserAgentUtil setUserAgent:_prevUserAgent lockToken:_userAgentLockToken];
|
||||
}
|
||||
|
||||
[self.navigationDelegate webViewDidFinishLoad:theWebView];
|
||||
}
|
||||
|
||||
- (void)webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error
|
||||
{
|
||||
// log fail message, stop spinner, update back/forward
|
||||
NSLog(@"webView:didFailLoadWithError - %i: %@", error.code, [error localizedDescription]);
|
||||
|
||||
self.backButton.enabled = theWebView.canGoBack;
|
||||
self.forwardButton.enabled = theWebView.canGoForward;
|
||||
[self.spinner stopAnimating];
|
||||
|
||||
self.addressLabel.text = NSLocalizedString(@"Load Error", nil);
|
||||
|
||||
[self.navigationDelegate webView:theWebView didFailLoadWithError:error];
|
||||
}
|
||||
|
||||
#pragma mark CDVScreenOrientationDelegate
|
||||
|
||||
- (BOOL)shouldAutorotate
|
||||
{
|
||||
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(shouldAutorotate)]) {
|
||||
return [self.orientationDelegate shouldAutorotate];
|
||||
}
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (NSUInteger)supportedInterfaceOrientations
|
||||
{
|
||||
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(supportedInterfaceOrientations)]) {
|
||||
return [self.orientationDelegate supportedInterfaceOrientations];
|
||||
}
|
||||
|
||||
return 1 << UIInterfaceOrientationPortrait;
|
||||
}
|
||||
|
||||
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
|
||||
{
|
||||
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(shouldAutorotateToInterfaceOrientation:)]) {
|
||||
return [self.orientationDelegate shouldAutorotateToInterfaceOrientation:interfaceOrientation];
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CDVInAppBrowserOptions
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init]) {
|
||||
// default values
|
||||
self.location = YES;
|
||||
self.toolbar = YES;
|
||||
self.closebuttoncaption = nil;
|
||||
self.toolbarposition = kInAppBrowserToolbarBarPositionBottom;
|
||||
|
||||
self.enableviewportscale = NO;
|
||||
self.mediaplaybackrequiresuseraction = NO;
|
||||
self.allowinlinemediaplayback = NO;
|
||||
self.keyboarddisplayrequiresuseraction = YES;
|
||||
self.suppressesincrementalrendering = NO;
|
||||
self.hidden = NO;
|
||||
self.disallowoverscroll = NO;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (CDVInAppBrowserOptions*)parseOptions:(NSString*)options
|
||||
{
|
||||
CDVInAppBrowserOptions* obj = [[CDVInAppBrowserOptions alloc] init];
|
||||
|
||||
// NOTE: this parsing does not handle quotes within values
|
||||
NSArray* pairs = [options componentsSeparatedByString:@","];
|
||||
|
||||
// parse keys and values, set the properties
|
||||
for (NSString* pair in pairs) {
|
||||
NSArray* keyvalue = [pair componentsSeparatedByString:@"="];
|
||||
|
||||
if ([keyvalue count] == 2) {
|
||||
NSString* key = [[keyvalue objectAtIndex:0] lowercaseString];
|
||||
NSString* value = [keyvalue objectAtIndex:1];
|
||||
NSString* value_lc = [value lowercaseString];
|
||||
|
||||
BOOL isBoolean = [value_lc isEqualToString:@"yes"] || [value_lc isEqualToString:@"no"];
|
||||
NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
|
||||
[numberFormatter setAllowsFloats:YES];
|
||||
BOOL isNumber = [numberFormatter numberFromString:value_lc] != nil;
|
||||
|
||||
// set the property according to the key name
|
||||
if ([obj respondsToSelector:NSSelectorFromString(key)]) {
|
||||
if (isNumber) {
|
||||
[obj setValue:[numberFormatter numberFromString:value_lc] forKey:key];
|
||||
} else if (isBoolean) {
|
||||
[obj setValue:[NSNumber numberWithBool:[value_lc isEqualToString:@"yes"]] forKey:key];
|
||||
} else {
|
||||
[obj setValue:value forKey:key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 2013 Canonical Ltd.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
import QtQuick 2.0
|
||||
import QtWebKit 3.0
|
||||
import Ubuntu.Components.Popups 0.1
|
||||
import Ubuntu.Components 0.1
|
||||
|
||||
Rectangle {
|
||||
anchors.fill: parent
|
||||
id: inappbrowser
|
||||
property string url1
|
||||
Rectangle {
|
||||
border.color: "black"
|
||||
width: parent.width
|
||||
height: urlEntry.height
|
||||
color: "gray"
|
||||
TextInput {
|
||||
id: urlEntry
|
||||
width: parent.width - closeButton.width
|
||||
text: url1
|
||||
activeFocusOnPress: false
|
||||
}
|
||||
Image {
|
||||
id: closeButton
|
||||
width: height
|
||||
x: parent.width - width
|
||||
height: parent.height
|
||||
source: "close.png"
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
onClicked: {
|
||||
root.exec("InAppBrowser", "close", [0, 0])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
WebView {
|
||||
width: parent.width
|
||||
y: urlEntry.height
|
||||
height: parent.height - y
|
||||
url: url1
|
||||
onLoadingChanged: {
|
||||
if (loadRequest.status) {
|
||||
root.exec("InAppBrowser", "loadFinished", [loadRequest.status])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 461 B |
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 2013 Canonical Ltd.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
#include <QQuickView>
|
||||
#include <QQuickItem>
|
||||
|
||||
#include "inappbrowser.h"
|
||||
#include <cordova.h>
|
||||
|
||||
Inappbrowser::Inappbrowser(Cordova *cordova): CPlugin(cordova), _eventCb(0) {
|
||||
}
|
||||
|
||||
const char code[] = "\
|
||||
var component, object; \
|
||||
function createObject() { \
|
||||
component = Qt.createComponent(%1); \
|
||||
if (component.status == Component.Ready) \
|
||||
finishCreation(); \
|
||||
else \
|
||||
component.statusChanged.connect(finishCreation); \
|
||||
} \
|
||||
function finishCreation() { \
|
||||
CordovaWrapper.object = component.createObject(root, \
|
||||
{root: root, cordova: cordova, url1: %2}); \
|
||||
} \
|
||||
createObject()";
|
||||
|
||||
const char EXIT_EVENT[] = "'exit'";
|
||||
const char LOADSTART_EVENT[] = "'loadstart'";
|
||||
const char LOADSTOP_EVENT[] = "'loadstop'";
|
||||
const char LOADERROR_EVENT[] = "'loaderror'";
|
||||
|
||||
void Inappbrowser::open(int cb, int, const QString &url, const QString &windowName, const QString &windowFeatures) {
|
||||
assert(_eventCb == 0);
|
||||
|
||||
_eventCb = cb;
|
||||
|
||||
QString path = m_cordova->get_app_dir() + "/../qml/InAppBrowser.qml";
|
||||
|
||||
// TODO: relative url
|
||||
QString qml = QString(code)
|
||||
.arg(CordovaInternal::format(path)).arg(CordovaInternal::format(url));
|
||||
m_cordova->execQML(qml);
|
||||
}
|
||||
|
||||
void Inappbrowser::show(int, int) {
|
||||
m_cordova->execQML("CordovaWrapper.object.visible = true");
|
||||
}
|
||||
|
||||
void Inappbrowser::close(int, int) {
|
||||
m_cordova->execQML("CordovaWrapper.object.destroy()");
|
||||
this->callbackWithoutRemove(_eventCb, EXIT_EVENT);
|
||||
_eventCb = 0;
|
||||
}
|
||||
|
||||
void Inappbrowser::injectStyleFile(int cb, int, const QString&, bool) {
|
||||
// TODO:
|
||||
qCritical() << "unimplemented " << __PRETTY_FUNCTION__;
|
||||
}
|
||||
|
||||
void Inappbrowser::injectStyleCode(int cb, int, const QString&, bool) {
|
||||
// TODO:
|
||||
qCritical() << "unimplemented " << __PRETTY_FUNCTION__;
|
||||
}
|
||||
|
||||
void Inappbrowser::injectScriptFile(int cb, int, const QString&, bool) {
|
||||
// TODO:
|
||||
qCritical() << "unimplemented " << __PRETTY_FUNCTION__;
|
||||
}
|
||||
|
||||
void Inappbrowser::injectScriptCode(int cb, int, const QString&, bool) {
|
||||
// TODO:
|
||||
qCritical() << "unimplemented " << __PRETTY_FUNCTION__;
|
||||
}
|
||||
|
||||
void Inappbrowser::loadFinished(int status) {
|
||||
if (status == 2) {
|
||||
this->callbackWithoutRemove(_eventCb, LOADERROR_EVENT);
|
||||
}
|
||||
if (status == 0) {
|
||||
this->callbackWithoutRemove(_eventCb, LOADSTART_EVENT);
|
||||
}
|
||||
if (status == 3) {
|
||||
this->callbackWithoutRemove(_eventCb, LOADSTOP_EVENT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 2013 Canonical Ltd.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
#ifndef INAPPBROWSER_H
|
||||
#define INAPPBROWSER_H
|
||||
|
||||
#include <QtCore>
|
||||
#include <cplugin.h>
|
||||
|
||||
class Inappbrowser: public CPlugin {
|
||||
Q_OBJECT
|
||||
public:
|
||||
Inappbrowser(Cordova *cordova);
|
||||
|
||||
virtual const QString fullName() override {
|
||||
return Inappbrowser::fullID();
|
||||
}
|
||||
|
||||
virtual const QString shortName() override {
|
||||
return "InAppBrowser";
|
||||
}
|
||||
|
||||
static const QString fullID() {
|
||||
return "InAppBrowser";
|
||||
}
|
||||
|
||||
public slots:
|
||||
void open(int cb, int, const QString &url, const QString &windowName, const QString &windowFeatures);
|
||||
void show(int, int);
|
||||
void close(int, int);
|
||||
void injectStyleFile(int cb, int, const QString&, bool);
|
||||
void injectStyleCode(int cb, int, const QString&, bool);
|
||||
void injectScriptFile(int cb, int, const QString&, bool);
|
||||
void injectScriptCode(int cb, int, const QString&, bool);
|
||||
|
||||
void loadFinished(int status);
|
||||
|
||||
private:
|
||||
int _eventCb;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,408 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Ink;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Animation;
|
||||
using System.Windows.Shapes;
|
||||
using Microsoft.Phone.Controls;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.Serialization;
|
||||
using WPCordovaClassLib.Cordova;
|
||||
using WPCordovaClassLib.Cordova.Commands;
|
||||
using WPCordovaClassLib.Cordova.JSON;
|
||||
using Microsoft.Phone.Shell;
|
||||
using Microsoft.Phone.Tasks;
|
||||
|
||||
namespace WPCordovaClassLib.Cordova.Commands
|
||||
{
|
||||
[DataContract]
|
||||
public class BrowserOptions
|
||||
{
|
||||
[DataMember]
|
||||
public string url;
|
||||
|
||||
[DataMember]
|
||||
public bool isGeolocationEnabled;
|
||||
}
|
||||
|
||||
public class InAppBrowser : BaseCommand
|
||||
{
|
||||
|
||||
private static WebBrowser browser;
|
||||
private static ApplicationBarIconButton backButton;
|
||||
private static ApplicationBarIconButton fwdButton;
|
||||
|
||||
protected ApplicationBar AppBar;
|
||||
|
||||
protected bool ShowLocation {get;set;}
|
||||
protected bool StartHidden {get;set;}
|
||||
|
||||
public void open(string options)
|
||||
{
|
||||
// reset defaults on ShowLocation + StartHidden features
|
||||
ShowLocation = true;
|
||||
StartHidden = false;
|
||||
|
||||
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
//BrowserOptions opts = JSON.JsonHelper.Deserialize<BrowserOptions>(options);
|
||||
string urlLoc = args[0];
|
||||
string target = args[1];
|
||||
string featString = args[2];
|
||||
|
||||
string[] features = featString.Split(',');
|
||||
foreach (string str in features)
|
||||
{
|
||||
try
|
||||
{
|
||||
string[] split = str.Split('=');
|
||||
switch (split[0])
|
||||
{
|
||||
case "location":
|
||||
ShowLocation = split[1].ToLower().StartsWith("yes");
|
||||
break;
|
||||
case "hidden":
|
||||
StartHidden = split[1].ToLower().StartsWith("yes");
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch(Exception)
|
||||
{
|
||||
// some sort of invalid param was passed, moving on ...
|
||||
}
|
||||
|
||||
}
|
||||
/*
|
||||
_self - opens in the Cordova WebView if url is in the white-list, else it opens in the InAppBrowser
|
||||
_blank - always open in the InAppBrowser
|
||||
_system - always open in the system web browser
|
||||
*/
|
||||
switch (target)
|
||||
{
|
||||
case "_blank":
|
||||
ShowInAppBrowser(urlLoc);
|
||||
break;
|
||||
case "_self":
|
||||
ShowCordovaBrowser(urlLoc);
|
||||
break;
|
||||
case "_system":
|
||||
ShowSystemBrowser(urlLoc);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void show(string options)
|
||||
{
|
||||
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
|
||||
|
||||
if (browser != null)
|
||||
{
|
||||
Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
browser.Visibility = Visibility.Visible;
|
||||
AppBar.IsVisible = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void injectScriptCode(string options)
|
||||
{
|
||||
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
|
||||
bool bCallback = false;
|
||||
if (bool.TryParse(args[1], out bCallback)) { };
|
||||
|
||||
string callbackId = args[2];
|
||||
|
||||
if (browser != null)
|
||||
{
|
||||
Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
var res = browser.InvokeScript("eval", new string[] { args[0] });
|
||||
|
||||
if (bCallback)
|
||||
{
|
||||
PluginResult result = new PluginResult(PluginResult.Status.OK, res.ToString());
|
||||
result.KeepCallback = false;
|
||||
this.DispatchCommandResult(result);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void injectScriptFile(string options)
|
||||
{
|
||||
Debug.WriteLine("Error : Windows Phone org.apache.cordova.inappbrowser does not currently support executeScript");
|
||||
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
// throw new NotImplementedException("Windows Phone does not currently support 'executeScript'");
|
||||
}
|
||||
|
||||
public void injectStyleCode(string options)
|
||||
{
|
||||
Debug.WriteLine("Error : Windows Phone org.apache.cordova.inappbrowser does not currently support insertCSS");
|
||||
return;
|
||||
|
||||
//string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
//bool bCallback = false;
|
||||
//if (bool.TryParse(args[1], out bCallback)) { };
|
||||
|
||||
//string callbackId = args[2];
|
||||
|
||||
//if (browser != null)
|
||||
//{
|
||||
//Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
//{
|
||||
// if (bCallback)
|
||||
// {
|
||||
// string cssInsertString = "try{(function(doc){var c = '<style>body{background-color:#ffff00;}</style>'; doc.head.innerHTML += c;})(document);}catch(ex){alert('oops : ' + ex.message);}";
|
||||
// //cssInsertString = cssInsertString.Replace("_VALUE_", args[0]);
|
||||
// Debug.WriteLine("cssInsertString = " + cssInsertString);
|
||||
// var res = browser.InvokeScript("eval", new string[] { cssInsertString });
|
||||
// if (bCallback)
|
||||
// {
|
||||
// PluginResult result = new PluginResult(PluginResult.Status.OK, res.ToString());
|
||||
// result.KeepCallback = false;
|
||||
// this.DispatchCommandResult(result);
|
||||
// }
|
||||
// }
|
||||
|
||||
//});
|
||||
//}
|
||||
}
|
||||
|
||||
public void injectStyleFile(string options)
|
||||
{
|
||||
Debug.WriteLine("Error : Windows Phone org.apache.cordova.inappbrowser does not currently support insertCSS");
|
||||
return;
|
||||
|
||||
//string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
//throw new NotImplementedException("Windows Phone does not currently support 'insertCSS'");
|
||||
}
|
||||
|
||||
|
||||
private void ShowCordovaBrowser(string url)
|
||||
{
|
||||
Uri loc = new Uri(url, UriKind.RelativeOrAbsolute);
|
||||
Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
|
||||
if (frame != null)
|
||||
{
|
||||
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
|
||||
if (page != null)
|
||||
{
|
||||
CordovaView cView = page.FindName("CordovaView") as CordovaView;
|
||||
if (cView != null)
|
||||
{
|
||||
WebBrowser br = cView.Browser;
|
||||
br.Navigate(loc);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ShowSystemBrowser(string url)
|
||||
{
|
||||
WebBrowserTask webBrowserTask = new WebBrowserTask();
|
||||
webBrowserTask.Uri = new Uri(url, UriKind.Absolute);
|
||||
webBrowserTask.Show();
|
||||
}
|
||||
|
||||
|
||||
private void ShowInAppBrowser(string url)
|
||||
{
|
||||
Uri loc = new Uri(url, UriKind.RelativeOrAbsolute);
|
||||
|
||||
Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (browser != null)
|
||||
{
|
||||
//browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
|
||||
browser.Navigate(loc);
|
||||
}
|
||||
else
|
||||
{
|
||||
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
|
||||
if (frame != null)
|
||||
{
|
||||
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
|
||||
|
||||
string baseImageUrl = "Images/";
|
||||
|
||||
if (page != null)
|
||||
{
|
||||
Grid grid = page.FindName("LayoutRoot") as Grid;
|
||||
if (grid != null)
|
||||
{
|
||||
browser = new WebBrowser();
|
||||
browser.IsScriptEnabled = true;
|
||||
browser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);
|
||||
|
||||
browser.Navigating += new EventHandler<NavigatingEventArgs>(browser_Navigating);
|
||||
browser.NavigationFailed += new System.Windows.Navigation.NavigationFailedEventHandler(browser_NavigationFailed);
|
||||
browser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(browser_Navigated);
|
||||
browser.Navigate(loc);
|
||||
|
||||
if (StartHidden)
|
||||
{
|
||||
browser.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
|
||||
//browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
|
||||
grid.Children.Add(browser);
|
||||
}
|
||||
|
||||
ApplicationBar bar = new ApplicationBar();
|
||||
bar.BackgroundColor = Colors.Gray;
|
||||
bar.IsMenuEnabled = false;
|
||||
|
||||
backButton = new ApplicationBarIconButton();
|
||||
backButton.Text = "Back";
|
||||
|
||||
backButton.IconUri = new Uri(baseImageUrl + "appbar.back.rest.png", UriKind.Relative);
|
||||
backButton.Click += new EventHandler(backButton_Click);
|
||||
bar.Buttons.Add(backButton);
|
||||
|
||||
|
||||
fwdButton = new ApplicationBarIconButton();
|
||||
fwdButton.Text = "Forward";
|
||||
fwdButton.IconUri = new Uri(baseImageUrl + "appbar.next.rest.png", UriKind.Relative);
|
||||
fwdButton.Click += new EventHandler(fwdButton_Click);
|
||||
bar.Buttons.Add(fwdButton);
|
||||
|
||||
ApplicationBarIconButton closeBtn = new ApplicationBarIconButton();
|
||||
closeBtn.Text = "Close";
|
||||
closeBtn.IconUri = new Uri(baseImageUrl + "appbar.close.rest.png", UriKind.Relative);
|
||||
closeBtn.Click += new EventHandler(closeBtn_Click);
|
||||
bar.Buttons.Add(closeBtn);
|
||||
|
||||
page.ApplicationBar = bar;
|
||||
bar.IsVisible = !StartHidden;
|
||||
AppBar = bar;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void browser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void fwdButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (browser != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
#if WP8
|
||||
browser.GoForward();
|
||||
#else
|
||||
browser.InvokeScript("execScript", "history.forward();");
|
||||
#endif
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void backButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (browser != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
#if WP8
|
||||
browser.GoBack();
|
||||
#else
|
||||
browser.InvokeScript("execScript", "history.back();");
|
||||
#endif
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void closeBtn_Click(object sender, EventArgs e)
|
||||
{
|
||||
this.close();
|
||||
}
|
||||
|
||||
|
||||
public void close(string options = "")
|
||||
{
|
||||
if (browser != null)
|
||||
{
|
||||
Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
|
||||
if (frame != null)
|
||||
{
|
||||
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
|
||||
if (page != null)
|
||||
{
|
||||
Grid grid = page.FindName("LayoutRoot") as Grid;
|
||||
if (grid != null)
|
||||
{
|
||||
grid.Children.Remove(browser);
|
||||
}
|
||||
page.ApplicationBar = null;
|
||||
}
|
||||
}
|
||||
browser = null;
|
||||
string message = "{\"type\":\"exit\"}";
|
||||
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
|
||||
result.KeepCallback = false;
|
||||
this.DispatchCommandResult(result);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
|
||||
{
|
||||
#if WP8
|
||||
if (browser != null)
|
||||
{
|
||||
backButton.IsEnabled = browser.CanGoBack;
|
||||
fwdButton.IsEnabled = browser.CanGoForward;
|
||||
|
||||
}
|
||||
#endif
|
||||
string message = "{\"type\":\"loadstop\", \"url\":\"" + e.Uri.OriginalString + "\"}";
|
||||
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
|
||||
result.KeepCallback = true;
|
||||
this.DispatchCommandResult(result);
|
||||
}
|
||||
|
||||
void browser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
|
||||
{
|
||||
string message = "{\"type\":\"error\",\"url\":\"" + e.Uri.OriginalString + "\"}";
|
||||
PluginResult result = new PluginResult(PluginResult.Status.ERROR, message);
|
||||
result.KeepCallback = true;
|
||||
this.DispatchCommandResult(result);
|
||||
}
|
||||
|
||||
void browser_Navigating(object sender, NavigatingEventArgs e)
|
||||
{
|
||||
string message = "{\"type\":\"loadstart\",\"url\":\"" + e.Uri.OriginalString + "\"}";
|
||||
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
|
||||
result.KeepCallback = true;
|
||||
this.DispatchCommandResult(result);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
var exec = require('cordova/exec');
|
||||
var channel = require('cordova/channel');
|
||||
var modulemapper = require('cordova/modulemapper');
|
||||
var urlutil = require('cordova/urlutil');
|
||||
|
||||
function InAppBrowser() {
|
||||
this.channels = {
|
||||
'loadstart': channel.create('loadstart'),
|
||||
'loadstop' : channel.create('loadstop'),
|
||||
'loaderror' : channel.create('loaderror'),
|
||||
'exit' : channel.create('exit')
|
||||
};
|
||||
}
|
||||
|
||||
InAppBrowser.prototype = {
|
||||
_eventHandler: function (event) {
|
||||
if (event.type in this.channels) {
|
||||
this.channels[event.type].fire(event);
|
||||
}
|
||||
},
|
||||
close: function (eventname) {
|
||||
exec(null, null, "InAppBrowser", "close", []);
|
||||
},
|
||||
show: function (eventname) {
|
||||
exec(null, null, "InAppBrowser", "show", []);
|
||||
},
|
||||
addEventListener: function (eventname,f) {
|
||||
if (eventname in this.channels) {
|
||||
this.channels[eventname].subscribe(f);
|
||||
}
|
||||
},
|
||||
removeEventListener: function(eventname, f) {
|
||||
if (eventname in this.channels) {
|
||||
this.channels[eventname].unsubscribe(f);
|
||||
}
|
||||
},
|
||||
|
||||
executeScript: function(injectDetails, cb) {
|
||||
if (injectDetails.code) {
|
||||
exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
|
||||
} else if (injectDetails.file) {
|
||||
exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
|
||||
} else {
|
||||
throw new Error('executeScript requires exactly one of code or file to be specified');
|
||||
}
|
||||
},
|
||||
|
||||
insertCSS: function(injectDetails, cb) {
|
||||
if (injectDetails.code) {
|
||||
exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
|
||||
} else if (injectDetails.file) {
|
||||
exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
|
||||
} else {
|
||||
throw new Error('insertCSS requires exactly one of code or file to be specified');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = function(strUrl, strWindowName, strWindowFeatures) {
|
||||
// Don't catch calls that write to existing frames (e.g. named iframes).
|
||||
if (window.frames && window.frames[strWindowName]) {
|
||||
var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
|
||||
return origOpenFunc.apply(window, arguments);
|
||||
}
|
||||
|
||||
strUrl = urlutil.makeAbsolute(strUrl);
|
||||
var iab = new InAppBrowser();
|
||||
var cb = function(eventname) {
|
||||
iab._eventHandler(eventname);
|
||||
};
|
||||
|
||||
exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
|
||||
return iab;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
/*jslint sloppy:true */
|
||||
/*global Windows:true, require, document, setTimeout, window, module */
|
||||
|
||||
|
||||
|
||||
var cordova = require('cordova'),
|
||||
channel = require('cordova/channel');
|
||||
|
||||
var browserWrap;
|
||||
|
||||
var IAB = {
|
||||
|
||||
close: function (win, lose) {
|
||||
if (browserWrap) {
|
||||
browserWrap.parentNode.removeChild(browserWrap);
|
||||
browserWrap = null;
|
||||
}
|
||||
},
|
||||
show: function (win, lose) {
|
||||
/* empty block, ran out of bacon?
|
||||
if (browserWrap) {
|
||||
|
||||
}*/
|
||||
},
|
||||
open: function (win, lose, args) {
|
||||
var strUrl = args[0],
|
||||
target = args[1],
|
||||
features = args[2],
|
||||
url,
|
||||
elem;
|
||||
|
||||
if (target === "_system") {
|
||||
url = new Windows.Foundation.Uri(strUrl);
|
||||
Windows.System.Launcher.launchUriAsync(url);
|
||||
} else if (target === "_blank") {
|
||||
if (!browserWrap) {
|
||||
browserWrap = document.createElement("div");
|
||||
browserWrap.style.position = "absolute";
|
||||
browserWrap.style.width = (window.innerWidth - 80) + "px";
|
||||
browserWrap.style.height = (window.innerHeight - 80) + "px";
|
||||
browserWrap.style.borderWidth = "40px";
|
||||
browserWrap.style.borderStyle = "solid";
|
||||
browserWrap.style.borderColor = "rgba(0,0,0,0.25)";
|
||||
|
||||
browserWrap.onclick = function () {
|
||||
setTimeout(function () {
|
||||
IAB.close();
|
||||
}, 0);
|
||||
};
|
||||
|
||||
document.body.appendChild(browserWrap);
|
||||
}
|
||||
|
||||
elem = document.createElement("iframe");
|
||||
elem.style.width = (window.innerWidth - 80) + "px";
|
||||
elem.style.height = (window.innerHeight - 80) + "px";
|
||||
elem.style.borderWidth = "0px";
|
||||
elem.name = "targetFrame";
|
||||
elem.src = strUrl;
|
||||
|
||||
window.addEventListener("resize", function () {
|
||||
if (browserWrap && elem) {
|
||||
elem.style.width = (window.innerWidth - 80) + "px";
|
||||
elem.style.height = (window.innerHeight - 80) + "px";
|
||||
}
|
||||
});
|
||||
|
||||
browserWrap.appendChild(elem);
|
||||
} else {
|
||||
window.location = strUrl;
|
||||
}
|
||||
|
||||
//var object = new WinJS.UI.HtmlControl(elem, { uri: strUrl });
|
||||
|
||||
},
|
||||
|
||||
injectScriptCode: function (code, bCB) {
|
||||
|
||||
// "(function(d) { var c = d.createElement('script'); c.src = %@; d.body.appendChild(c); })(document)"
|
||||
},
|
||||
|
||||
injectScriptFile: function (file, bCB) {
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = IAB;
|
||||
|
||||
|
||||
require("cordova/windows8/commandProxy").add("InAppBrowser", module.exports);
|
||||
@@ -6,17 +6,22 @@ class HomeController
|
||||
constructor: (@$scope, @$location, BookService, ScanService, @$ionicLoading, @$ionicActionSheet, @RecommendService)->
|
||||
if isUserLogedIn()
|
||||
showLoading(@$scope, @$ionicLoading)
|
||||
BookService.getBooks().success (result)=>
|
||||
@$scope.books = result.books
|
||||
@$scope.enableBackButton = false
|
||||
@$scope.rightButtons = [
|
||||
{
|
||||
type: 'button icon ion-shuffle'
|
||||
tap: (e) =>
|
||||
@showRecommendActionSheet()
|
||||
}
|
||||
]
|
||||
@$scope.loading.hide();
|
||||
@$scope.title = 'Libr - 你可能喜欢的书'
|
||||
@$scope.enableBackButton = false
|
||||
@$scope.rightButtons = [
|
||||
{
|
||||
type: 'button icon ion-shuffle'
|
||||
tap: (e) =>
|
||||
@showRecommendActionSheet()
|
||||
}
|
||||
]
|
||||
@RecommendService.popularBooksForMe (result)=>
|
||||
if result.length is 0
|
||||
alert '请先添加一些你阅读的书,再来查看推荐吧'
|
||||
return
|
||||
else
|
||||
@$scope.books = result
|
||||
@$scope.loading.hide();
|
||||
else
|
||||
@$location.path '/tab/settings'
|
||||
return
|
||||
@@ -42,11 +47,19 @@ class HomeController
|
||||
cancelText: '取消'
|
||||
cancel: ()->
|
||||
console.log('CANCELLED')
|
||||
buttonClicked: (index)->
|
||||
console.log('BUTTON CLICKED', index)
|
||||
buttonClicked: (index)=>
|
||||
console.log "#{index} has been taped"
|
||||
@changeRecommend index
|
||||
true
|
||||
destructiveButtonClicked: ()->
|
||||
console.log('DESTRUCT')
|
||||
true
|
||||
}
|
||||
changeRecommend: (index)=>
|
||||
@RecommendService.changeRecommendAction index, (result)=>
|
||||
if result.length is 0
|
||||
alert '喔,看来附近还没有好书推荐,快去推荐你的朋友也来使用吧!'
|
||||
else
|
||||
@$scope.books = result
|
||||
listArray = JSON.parse(localStorage.getItem 'recommend_action_sheet_full_arr')
|
||||
@$scope.title = 'Libr-' + listArray[index].text
|
||||
libr.controller 'HomeCtrl', HomeController
|
||||
@@ -16,22 +16,30 @@
|
||||
this.$ionicLoading = $ionicLoading;
|
||||
this.$ionicActionSheet = $ionicActionSheet;
|
||||
this.RecommendService = RecommendService;
|
||||
this.changeRecommend = __bind(this.changeRecommend, this);
|
||||
this.showRecommendActionSheet = __bind(this.showRecommendActionSheet, this);
|
||||
if (isUserLogedIn()) {
|
||||
showLoading(this.$scope, this.$ionicLoading);
|
||||
BookService.getBooks().success((function(_this) {
|
||||
this.$scope.title = 'Libr - 你可能喜欢的书';
|
||||
this.$scope.enableBackButton = false;
|
||||
this.$scope.rightButtons = [
|
||||
{
|
||||
type: 'button icon ion-shuffle',
|
||||
tap: (function(_this) {
|
||||
return function(e) {
|
||||
return _this.showRecommendActionSheet();
|
||||
};
|
||||
})(this)
|
||||
}
|
||||
];
|
||||
this.RecommendService.popularBooksForMe((function(_this) {
|
||||
return function(result) {
|
||||
_this.$scope.books = result.books;
|
||||
_this.$scope.enableBackButton = false;
|
||||
_this.$scope.rightButtons = [
|
||||
{
|
||||
type: 'button icon ion-shuffle',
|
||||
tap: function(e) {
|
||||
return _this.showRecommendActionSheet();
|
||||
}
|
||||
}
|
||||
];
|
||||
return _this.$scope.loading.hide();
|
||||
if (result.length === 0) {
|
||||
alert('请先添加一些你阅读的书,再来查看推荐吧');
|
||||
} else {
|
||||
_this.$scope.books = result;
|
||||
return _this.$scope.loading.hide();
|
||||
}
|
||||
};
|
||||
})(this));
|
||||
} else {
|
||||
@@ -67,17 +75,34 @@
|
||||
cancel: function() {
|
||||
return console.log('CANCELLED');
|
||||
},
|
||||
buttonClicked: function(index) {
|
||||
console.log('BUTTON CLICKED', index);
|
||||
return true;
|
||||
},
|
||||
buttonClicked: (function(_this) {
|
||||
return function(index) {
|
||||
console.log("" + index + " has been taped");
|
||||
_this.changeRecommend(index);
|
||||
return true;
|
||||
};
|
||||
})(this),
|
||||
destructiveButtonClicked: function() {
|
||||
console.log('DESTRUCT');
|
||||
return true;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
HomeController.prototype.changeRecommend = function(index) {
|
||||
return this.RecommendService.changeRecommendAction(index, (function(_this) {
|
||||
return function(result) {
|
||||
var listArray;
|
||||
if (result.length === 0) {
|
||||
return alert('喔,看来附近还没有好书推荐,快去推荐你的朋友也来使用吧!');
|
||||
} else {
|
||||
_this.$scope.books = result;
|
||||
listArray = JSON.parse(localStorage.getItem('recommend_action_sheet_full_arr'));
|
||||
return _this.$scope.title = 'Libr-' + listArray[index].text;
|
||||
}
|
||||
};
|
||||
})(this));
|
||||
};
|
||||
|
||||
return HomeController;
|
||||
|
||||
})();
|
||||
|
||||
@@ -6,6 +6,7 @@ class SettingsController
|
||||
constructor: (@$scope, @$ionicModal, @AuthService, @$state) ->
|
||||
@$scope.login = @login
|
||||
@$scope.logout = @logout
|
||||
@$scope.feedback = @feedback
|
||||
if isUserLogedIn() then @$scope.isLogedIn = true else @$scope.isLogedIn = false
|
||||
|
||||
|
||||
@@ -21,6 +22,9 @@ class SettingsController
|
||||
localStorage.removeItem 'token'
|
||||
@$state.go 'login'
|
||||
|
||||
feedback: ->
|
||||
window.open('https://jinshuju.net/f/F96z3s', '_blank', 'location=no')
|
||||
|
||||
isUserLogedIn = ()->
|
||||
if localStorage.getItem('token') isnt null and localStorage.getItem('email') isnt null
|
||||
true
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
this.login = __bind(this.login, this);
|
||||
this.$scope.login = this.login;
|
||||
this.$scope.logout = this.logout;
|
||||
this.$scope.feedback = this.feedback;
|
||||
if (isUserLogedIn()) {
|
||||
this.$scope.isLogedIn = true;
|
||||
} else {
|
||||
@@ -42,6 +43,10 @@
|
||||
return this.$state.go('login');
|
||||
};
|
||||
|
||||
SettingsController.prototype.feedback = function() {
|
||||
return window.open('https://jinshuju.net/f/F96z3s', '_blank', 'location=no');
|
||||
};
|
||||
|
||||
isUserLogedIn = function() {
|
||||
if (localStorage.getItem('token') !== null && localStorage.getItem('email') !== null) {
|
||||
return true;
|
||||
|
||||
@@ -1,18 +1,60 @@
|
||||
libr = angular.module 'libr.services.recommend', []
|
||||
|
||||
class RecommendService
|
||||
baseUrl = 'http://libr.herokuapp.com/api/v1'
|
||||
email = localStorage.getItem 'email'
|
||||
token = localStorage.getItem 'token'
|
||||
|
||||
@$injector: ['GeolocationService']
|
||||
constructor: (@GeolocationService)->
|
||||
@$injector: ['GeolocationService', '$http']
|
||||
constructor: (@GeolocationService, @$http)->
|
||||
|
||||
getActionSheetList: ()->
|
||||
actionList = []
|
||||
actionList.push {text: "我可能喜欢的书"}
|
||||
actionList.push {text: "你可能喜欢的书"}
|
||||
@GeolocationService.getLocations (locations)=>
|
||||
locations = locations.map (location)->
|
||||
locationIds = []
|
||||
locations.map (location)->
|
||||
locationIds.push location.id
|
||||
location = {text: "#{location.address}附近流行的书"}
|
||||
actionList.push location
|
||||
localStorage.setItem 'recommend_action_sheet_arr', JSON.stringify(locationIds)
|
||||
localStorage.setItem 'recommend_action_sheet_full_arr', JSON.stringify(actionList)
|
||||
actionList
|
||||
|
||||
|
||||
popularBooksForMe: (callback, error)->
|
||||
@$http(
|
||||
url: "#{baseUrl}/recommend/me?user_email=#{email}&user_token=#{token}"
|
||||
method: 'GET'
|
||||
cache: true
|
||||
)
|
||||
.success (data, status, headers, config)->
|
||||
callback data
|
||||
.error (data)->
|
||||
error data
|
||||
|
||||
popularBooksAroundMe: (locationId, callback, error)=>
|
||||
@$http(
|
||||
url: "#{baseUrl}/recommend/locations/#{locationId}?user_email=#{email}&user_token=#{token}"
|
||||
method: 'GET'
|
||||
cache: true
|
||||
)
|
||||
.success (data, status, headers, config)->
|
||||
console.log '数据', data
|
||||
callback data
|
||||
.error (data)->
|
||||
error data
|
||||
|
||||
changeRecommendAction: (index, callback, error)=>
|
||||
if index is 0
|
||||
@popularBooksForMe callback, error
|
||||
else
|
||||
locations = JSON.parse(localStorage.getItem('recommend_action_sheet_arr'))
|
||||
@popularBooksAroundMe locations[index - 1], (result)->
|
||||
console.log 'callback....', result
|
||||
callback result
|
||||
, (errorMessage)->
|
||||
error errorMessage
|
||||
|
||||
|
||||
libr.service 'RecommendService', RecommendService
|
||||
|
||||
@@ -1,35 +1,92 @@
|
||||
// Generated by CoffeeScript 1.7.1
|
||||
(function() {
|
||||
var RecommendService, libr;
|
||||
var RecommendService, libr,
|
||||
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
|
||||
|
||||
libr = angular.module('libr.services.recommend', []);
|
||||
|
||||
RecommendService = (function() {
|
||||
RecommendService.$injector = ['GeolocationService'];
|
||||
var baseUrl, email, token;
|
||||
|
||||
function RecommendService(GeolocationService) {
|
||||
baseUrl = 'http://libr.herokuapp.com/api/v1';
|
||||
|
||||
email = localStorage.getItem('email');
|
||||
|
||||
token = localStorage.getItem('token');
|
||||
|
||||
RecommendService.$injector = ['GeolocationService', '$http'];
|
||||
|
||||
function RecommendService(GeolocationService, $http) {
|
||||
this.GeolocationService = GeolocationService;
|
||||
this.$http = $http;
|
||||
this.changeRecommendAction = __bind(this.changeRecommendAction, this);
|
||||
this.popularBooksAroundMe = __bind(this.popularBooksAroundMe, this);
|
||||
}
|
||||
|
||||
RecommendService.prototype.getActionSheetList = function() {
|
||||
var actionList;
|
||||
actionList = [];
|
||||
actionList.push({
|
||||
text: "我可能喜欢的书"
|
||||
text: "你可能喜欢的书"
|
||||
});
|
||||
this.GeolocationService.getLocations((function(_this) {
|
||||
return function(locations) {
|
||||
return locations = locations.map(function(location) {
|
||||
var locationIds;
|
||||
locationIds = [];
|
||||
locations.map(function(location) {
|
||||
locationIds.push(location.id);
|
||||
location = {
|
||||
text: "" + location.address + "附近流行的书"
|
||||
};
|
||||
return actionList.push(location);
|
||||
});
|
||||
localStorage.setItem('recommend_action_sheet_arr', JSON.stringify(locationIds));
|
||||
return localStorage.setItem('recommend_action_sheet_full_arr', JSON.stringify(actionList));
|
||||
};
|
||||
})(this));
|
||||
return actionList;
|
||||
};
|
||||
|
||||
RecommendService.prototype.popularBooksForMe = function(callback, error) {
|
||||
return this.$http({
|
||||
url: "" + baseUrl + "/recommend/me?user_email=" + email + "&user_token=" + token,
|
||||
method: 'GET',
|
||||
cache: true
|
||||
}).success(function(data, status, headers, config) {
|
||||
return callback(data);
|
||||
}).error(function(data) {
|
||||
return error(data);
|
||||
});
|
||||
};
|
||||
|
||||
RecommendService.prototype.popularBooksAroundMe = function(locationId, callback, error) {
|
||||
return this.$http({
|
||||
url: "" + baseUrl + "/recommend/locations/" + locationId + "?user_email=" + email + "&user_token=" + token,
|
||||
method: 'GET',
|
||||
cache: true
|
||||
}).success(function(data, status, headers, config) {
|
||||
console.log('数据', data);
|
||||
return callback(data);
|
||||
}).error(function(data) {
|
||||
return error(data);
|
||||
});
|
||||
};
|
||||
|
||||
RecommendService.prototype.changeRecommendAction = function(index, callback, error) {
|
||||
var locations;
|
||||
if (index === 0) {
|
||||
return this.popularBooksForMe(callback, error);
|
||||
} else {
|
||||
locations = JSON.parse(localStorage.getItem('recommend_action_sheet_arr'));
|
||||
return this.popularBooksAroundMe(locations[index - 1], function(result) {
|
||||
console.log('callback....', result);
|
||||
return callback(result);
|
||||
}, function(errorMessage) {
|
||||
return error(errorMessage);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return RecommendService;
|
||||
|
||||
})();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<ion-view title="'Libr'" hide-back-button="false" left-buttons="leftButtons" right-buttons="rightButtons">
|
||||
<ion-view title="title" hide-back-button="false" left-buttons="leftButtons" right-buttons="rightButtons">
|
||||
<ion-content has-header="true" has-tabs="true" padding="true">
|
||||
<div class="list">
|
||||
<a ng-repeat="book in books" class="item item-thumbnail-left" href="#/book/{{book.isbn}}">
|
||||
@@ -7,6 +7,7 @@
|
||||
<h2>{{ book.name }}</h2>
|
||||
|
||||
<p>{{book.author}}</p>
|
||||
<p>有{{book.sort_id}}人看过</p>
|
||||
</a>
|
||||
</div>
|
||||
</ion-content>
|
||||
|
||||
@@ -2,18 +2,6 @@ x<ion-view title="'设置'">
|
||||
<ion-content has-header="true" has-tabs="true" padding="true">
|
||||
<div class="list">
|
||||
|
||||
<a class="item item-icon-left" href="#">
|
||||
<i class="icon ion-email"></i>
|
||||
Check mail
|
||||
<span class="badge badge-assertive">0</span>
|
||||
</a>
|
||||
|
||||
<a class="item item-icon-left item-icon-right" href="#">
|
||||
<i class="icon ion-chatbubble-working"></i>
|
||||
Call Ma
|
||||
<i class="icon ion-ios7-telephone-outline"></i>
|
||||
</a>
|
||||
|
||||
<a class="item item-icon-left">
|
||||
<i class="icon ion-person-stalker"></i>
|
||||
{{isLogedIn === true? '用户已登录': '请先登录' }}
|
||||
@@ -23,6 +11,20 @@ x<ion-view title="'设置'">
|
||||
<i class="icon ion-log-out"></i>
|
||||
注销登录
|
||||
</a>
|
||||
<a class="item item-icon-left" href="#">
|
||||
<i class="icon ion-email"></i>
|
||||
系统消息
|
||||
<span class="badge badge-assertive">0</span>
|
||||
</a>
|
||||
<a class="item item-icon-left" href="#" ng-click="feedback()">
|
||||
<i class="icon ion-heart"></i>
|
||||
给我们提供反馈
|
||||
</a>
|
||||
<a class="item item-icon-left" href="#">
|
||||
<i class="icon ion-information-circled"></i>
|
||||
关于
|
||||
</a>
|
||||
|
||||
</div>
|
||||
</ion-content>
|
||||
</ion-view>
|
||||
|
||||