Skip to content

Commit

Permalink
Adding custom header support, sourced from:
Browse files Browse the repository at this point in the history
  • Loading branch information
hvaughan3 committed Apr 30, 2019
1 parent 22739ba commit 281a110
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 23 deletions.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ simply hook `window.open` during initialization. For example:
Opens a URL in a new `InAppBrowser` instance, the current browser
instance, or the system browser.

var ref = cordova.InAppBrowser.open(url, target, options);
var ref = cordova.InAppBrowser.open(url, target, options, headers);

- __ref__: Reference to the `InAppBrowser` window when the target is set to `'_blank'`. _(InAppBrowser)_

Expand Down Expand Up @@ -133,6 +133,9 @@ instance, or the system browser.
- __mediaPlaybackRequiresUserAction__: Set to `yes` to prevent HTML5 audio or video from autoplaying (defaults to `no`).
- __shouldPauseOnSuspend__: Set to `yes` to make InAppBrowser WebView to pause/resume with the app to stop background audio (this may be required to avoid Google Play issues like described in [CB-11013](https://issues.apache.org/jira/browse/CB-11013)).
- __useWideViewPort__: Sets whether the WebView should enable support for the "viewport" HTML meta tag or should use a wide viewport. When the value of the setting is `no`, the layout width is always set to the width of the WebView control in device-independent (CSS) pixels. When the value is `yes` and the page contains the viewport meta tag, the value of the width specified in the tag is used. If the page does not contain the tag or does not provide a width, then a wide viewport will be used. (defaults to `yes`).
- __headers__: Headers for the http request. Optional. _(String)_ or _(javascript object)_
- _(String)_: headers must be in `header=value` form, separated by commas : `header1=value1,header2=value2`. don't use _(String)_ if commas or equals can be contained in headers or values.
- _(javascript object)_: headers are stored in object's properties like this `{ 'header1': 'value1', 'header2': 'value2'}`. this storage always works even if headers contain commas or equals.

iOS supports these additional options:

Expand All @@ -156,6 +159,9 @@ instance, or the system browser.
- __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.
- __hidespinner__: Set to `yes` or `no` to change the visibility of the loading indicator (defaults to `no`).
- __headers__: Headers for the http request. Optional. _(String)_ or _(javascript object)_
- _(String)_: headers must be in `header=value` form, separated by commas : `header1=value1,header2=value2`. don't use _(String)_ if commas or equals can be contained in headers or values.
- _(javascript object)_: headers are stored in object's properties like this `{ 'header1': 'value1', 'header2': 'value2'}`. this storage always works even if headers contain commas or equals.

Windows supports these additional options:

Expand Down
47 changes: 37 additions & 10 deletions src/android/InAppBrowser.java
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ public boolean execute(String action, CordovaArgs args, final CallbackContext ca
}
final String target = t;
final HashMap<String, String> features = parseFeature(args.optString(2));
final HashMap<String, String> headers = parseHeaders(args.optString(3));

LOG.d(LOG_TAG, "target = " + target);

Expand Down Expand Up @@ -223,7 +224,7 @@ else if (url.startsWith(WebView.SCHEME_TEL))
// load in InAppBrowser
else {
LOG.d(LOG_TAG, "loading in InAppBrowser");
result = showWebPage(url, features);
result = showWebPage(url, features, headers);
}
}
// SYSTEM
Expand All @@ -234,7 +235,7 @@ else if (SYSTEM.equals(target)) {
// BLANK - or anything else
else {
LOG.d(LOG_TAG, "in blank");
result = showWebPage(url, features);
result = showWebPage(url, features, headers);
}

PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
Expand Down Expand Up @@ -379,7 +380,7 @@ private void injectDeferredObject(String source, String jsWrapper) {
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);
inAppWebView.loadUrl("javascript:" + finalScriptToInject, null);
} else {
inAppWebView.evaluateJavascript(finalScriptToInject, null);
}
Expand Down Expand Up @@ -418,6 +419,32 @@ private HashMap<String, String> parseFeature(String optString) {
}
}

/**
* Put the headers string into a hash map
*
* @param headersString string of headers comma separated (key=value)
* @return map of headers
*/
private HashMap<String, String> parseHeaders(String headersString) {
if (headersString.equals(NULL)) {
return null;
}

HashMap<String, String> map = new HashMap<String, String>();
StringTokenizer headers = new StringTokenizer(headersString, ",");
StringTokenizer header;
while(headers.hasMoreElements()) {
header = new StringTokenizer(headers.nextToken(), "=");
if (header.hasMoreElements()) {
String key = header.nextToken().replace("@e","=").replace("@c", ",").replace("@a","@");
String value = header.nextToken().replace("@e","=").replace("@c", ",").replace("@a","@");
map.put(key, value);
}
}

return map;
}

/**
* Display a new browser with the specified URL.
*
Expand Down Expand Up @@ -465,19 +492,19 @@ public void run() {
public void onPageFinished(WebView view, String url) {
if (dialog != null) {
try {
dialog.dismiss();
dialog.dismiss();
} catch (IllegalArgumentException e) {
LOG.d(LOG_TAG, "Exception dismissing window: " + e.getLocalizedMessage());
}

dialog = null;
}
}
});
// NB: From SDK 19: "If you call methods on WebView from any thread
// other than your app's UI thread, it can cause unexpected results."
// http://developer.android.com/guide/webapps/migrating.html#Threads
childView.loadUrl("about:blank");
childView.loadUrl("about:blank", null);

try {
JSONObject obj = new JSONObject();
Expand Down Expand Up @@ -534,9 +561,9 @@ private void navigate(String url) {
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);

if (!url.startsWith("http") && !url.startsWith("file:")) {
this.inAppWebView.loadUrl("http://" + url);
this.inAppWebView.loadUrl("http://" + url, null);
} else {
this.inAppWebView.loadUrl(url);
this.inAppWebView.loadUrl(url, null);
}
this.inAppWebView.requestFocus();
}
Expand All @@ -561,7 +588,7 @@ private InAppBrowser getInAppBrowser(){
* @param url the url to load.
* @param features jsonObject
*/
public String showWebPage(final String url, HashMap<String, String> features) {
public String showWebPage(final String url, HashMap<String, String> features, final HashMap<String, String> headers) {
// Determine if we should hide the location bar.
showLocationBar = true;
enableZoomControls = true;
Expand Down Expand Up @@ -986,7 +1013,7 @@ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType)
CookieManager.getInstance().setAcceptThirdPartyCookies(inAppWebView,true);
}

inAppWebView.loadUrl(url);
inAppWebView.loadUrl(url, headers);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(useWideViewPort);
Expand Down
3 changes: 2 additions & 1 deletion src/ios/CDVInAppBrowser.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
@property (nonatomic, assign) BOOL disallowoverscroll;

+ (CDVInAppBrowserOptions*)parseOptions:(NSString*)options;
+ (NSMutableURLRequest*)createRequest:(NSURL*)url headers:(NSString*)headers;

@end

Expand Down Expand Up @@ -103,7 +104,7 @@
@property (nonatomic) NSURL* currentURL;

- (void)close;
- (void)navigateTo:(NSURL*)url;
- (void)navigateTo:(NSURL*)url headers:(NSString *)headers;
- (void)showLocationBar:(BOOL)show;
- (void)showToolBar:(BOOL)show : (NSString *) toolbarPosition;
- (void)setCloseButtonTitle:(NSString*)title : (NSString*) colorString;
Expand Down
37 changes: 28 additions & 9 deletions src/ios/CDVInAppBrowser.m
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ - (void)open:(CDVInvokedUrlCommand*)command
NSString* url = [command argumentAtIndex:0];
NSString* target = [command argumentAtIndex:1 withDefault:kInAppBrowserTargetSelf];
NSString* options = [command argumentAtIndex:2 withDefault:@"" andClass:[NSString class]];
NSString* headers = [command argumentAtIndex:3 withDefault:@"" andClass:[NSString class]];

self.callbackId = command.callbackId;

Expand All @@ -100,11 +101,11 @@ - (void)open:(CDVInvokedUrlCommand*)command
}

if ([target isEqualToString:kInAppBrowserTargetSelf]) {
[self openInCordovaWebView:absoluteUrl withOptions:options];
[self openInCordovaWebView:absoluteUrl withOptions:options withHeaders:headers];
} else if ([target isEqualToString:kInAppBrowserTargetSystem]) {
[self openInSystem:absoluteUrl];
} else { // _blank or anything else
[self openInInAppBrowser:absoluteUrl withOptions:options];
[self openInInAppBrowser:absoluteUrl withOptions:options withHeaders:headers];
}

pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
Expand All @@ -116,7 +117,7 @@ - (void)open:(CDVInvokedUrlCommand*)command
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)openInInAppBrowser:(NSURL*)url withOptions:(NSString*)options
- (void)openInInAppBrowser:(NSURL*)url withOptions:(NSString*)options withHeaders:(NSString*)headers
{
CDVInAppBrowserOptions* browserOptions = [CDVInAppBrowserOptions parseOptions:options];

Expand Down Expand Up @@ -209,7 +210,7 @@ - (void)openInInAppBrowser:(NSURL*)url withOptions:(NSString*)options
self.inAppBrowserViewController.webView.suppressesIncrementalRendering = browserOptions.suppressesincrementalrendering;
}

[self.inAppBrowserViewController navigateTo:url];
[self.inAppBrowserViewController navigateTo:url headers:headers];
if (!browserOptions.hidden) {
[self show:nil];
}
Expand Down Expand Up @@ -279,9 +280,9 @@ - (void)hide:(CDVInvokedUrlCommand*)command
});
}

- (void)openInCordovaWebView:(NSURL*)url withOptions:(NSString*)options
- (void)openInCordovaWebView:(NSURL*)url withOptions:(NSString*)options withHeaders:(NSString*)headers
{
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest* request = [CDVInAppBrowserOptions createRequest:url headers:headers];

#ifdef __CORDOVA_4_0_0
// the webview engine itself will filter for this according to <allow-navigation> policy
Expand All @@ -291,7 +292,7 @@ - (void)openInCordovaWebView:(NSURL*)url withOptions:(NSString*)options
if ([self.commandDelegate URLIsWhitelisted:url]) {
[self.webView loadRequest:request];
} else { // this assumes the InAppBrowser can be excepted from the white-list
[self openInInAppBrowser:url withOptions:options];
[self openInInAppBrowser:url withOptions:options withHeaders:headers];
}
#endif
}
Expand Down Expand Up @@ -894,9 +895,9 @@ - (void)close
});
}

- (void)navigateTo:(NSURL*)url
- (void)navigateTo:(NSURL*)url headers:(NSString*)headers
{
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest* request = [CDVInAppBrowserOptions createRequest:url headers:headers];

if (_userAgentLockToken != 0) {
[self.webView loadRequest:request];
Expand Down Expand Up @@ -1127,6 +1128,24 @@ + (CDVInAppBrowserOptions*)parseOptions:(NSString*)options
return obj;
}

+ (NSMutableURLRequest*)createRequest:(NSURL*)url headers:(NSString*)headers
{
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
if (headers != nil) {
NSArray* pairs = [headers componentsSeparatedByString:@","];
for (NSString* pair in pairs) {
NSArray* keyvalue = [pair componentsSeparatedByString:@"="];

if ([keyvalue count] == 2) {
NSString* key = [[[[keyvalue objectAtIndex:0] stringByReplacingOccurrencesOfString:@"@e" withString:@"="] stringByReplacingOccurrencesOfString:@"@c" withString:@","] stringByReplacingOccurrencesOfString:@"@a" withString:@"@"];
NSString* value = [[[[keyvalue objectAtIndex:1] stringByReplacingOccurrencesOfString:@"@e" withString:@"="] stringByReplacingOccurrencesOfString:@"@c" withString:@","] stringByReplacingOccurrencesOfString:@"@a" withString:@"@"];
[request setValue:value forHTTPHeaderField:key];
}
}
}
return request;
}

@end

@implementation CDVInAppBrowserNavigationController : UINavigationController
Expand Down
26 changes: 24 additions & 2 deletions www/inappbrowser.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
}
};

module.exports = function (strUrl, strWindowName, strWindowFeatures, callbacks) {
module.exports = function (strUrl, strWindowName, strWindowFeatures, windowHeaders, callbacks) {
// 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');
Expand All @@ -107,9 +107,31 @@
iab._eventHandler(eventname);
};

var strWindowHeaders = '';

if (windowHeaders) {
if (typeof windowHeaders === 'string' || windowHeaders instanceof String) {
strWindowHeaders = windowHeaders.replace(/@/gi, '@a');
} else {
var first = true;
for (var k in windowHeaders) {
if (windowHeaders.hasOwnProperty(k)) {
var key = k.replace(/@/gi, '@a').replace(/,/gi, '@c').replace(/=/gi, '@e');
var value = windowHeaders[k].toString().replace(/@/gi, '@a').replace(/,/gi, '@c').replace(/=/gi, '@e');
if (first) {
first = false;
} else {
strWindowHeaders += ',';
}
strWindowHeaders += key + '=' + value;
}
}
}
}

strWindowFeatures = strWindowFeatures || '';

exec(cb, cb, 'InAppBrowser', 'open', [strUrl, strWindowName, strWindowFeatures]);
exec(cb, cb, 'InAppBrowser', 'open', [strUrl, strWindowName, strWindowFeatures, strWindowHeaders]);
return iab;
};
})();

0 comments on commit 281a110

Please # to comment.