Skip to content

Commit

Permalink
Add headers parameter
Browse files Browse the repository at this point in the history
Fix No known class method for selector 'requestWithURL:headers:' (+4 squashed commits)
Squashed commits:
[128ec0c] remove }
[4423404] Added headers to type

* index.d.ts - added headers parameter
[642d4da] fix indentation for header and strWindowHeaders
[c77f20d] PR issue-apache#361 (iOS & Android) add request headers support

iharyan@b393577
  • Loading branch information
Sébastien Rufiange authored and syrine kriaa committed Jan 28, 2022
1 parent 10f2ad7 commit e20c12b
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 24 deletions.
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,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 @@ -156,7 +156,10 @@ instance, or the system browser.
- __hardwareback__: works the same way as on Android platform.
- __fullscreen__: set to `yes` to create the browser control without a border around it. Please note that if __location=no__ is also specified, there will be no control presented to user to close IAB window.


- __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.

### Supported Platforms

- Android
Expand Down
42 changes: 34 additions & 8 deletions src/android/InAppBrowser.java
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,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 @@ -231,7 +232,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 @@ -242,7 +243,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 All @@ -269,7 +270,7 @@ public void run() {
} else {
((InAppBrowserClient)inAppWebView.getWebViewClient()).waitForBeforeload = false;
}
inAppWebView.loadUrl(url);
inAppWebView.loadUrl(url, null);
}
});
}
Expand Down Expand Up @@ -444,6 +445,31 @@ 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;
} else {
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 @@ -539,7 +565,7 @@ public void onPageFinished(WebView view, String url) {
// 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 @@ -596,9 +622,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 @@ -623,7 +649,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;
showZoomControls = true;
Expand Down Expand Up @@ -992,7 +1018,7 @@ public void postMessage(String data) {
// Enable Thirdparty Cookies
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
1 change: 1 addition & 0 deletions src/ios/CDVInAppBrowserOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,6 @@
@property (nonatomic, copy) NSString* beforeload;

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

@end
20 changes: 20 additions & 0 deletions src/ios/CDVInAppBrowserOptions.m
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,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
2 changes: 1 addition & 1 deletion src/ios/CDVWKInAppBrowser.h
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,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 : (int) buttonIndex;
Expand Down
21 changes: 11 additions & 10 deletions src/ios/CDVWKInAppBrowser.m
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ - (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;

if (url != nil) {
Expand All @@ -108,11 +109,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 @@ -124,7 +125,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 @@ -257,7 +258,7 @@ - (void)openInInAppBrowser:(NSURL*)url withOptions:(NSString*)options
}
_waitForBeforeload = ![_beforeload isEqualToString:@""];

[self.inAppBrowserViewController navigateTo:url];
[self.inAppBrowserViewController navigateTo:url headers:headers];
if (!browserOptions.hidden) {
[self show:nil withNoAnimate:browserOptions.hidden];
}
Expand Down Expand Up @@ -349,9 +350,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];
// the webview engine itself will filter for this according to <allow-navigation> policy
// in config.xml for cordova-ios-4.0
[self.webViewEngine loadRequest:request];
Expand Down Expand Up @@ -384,7 +385,7 @@ - (void)loadAfterBeforeload:(CDVInvokedUrlCommand*)command
NSURL* url = [NSURL URLWithString:urlStr];
//_beforeload = @"";
_waitForBeforeload = NO;
[self.inAppBrowserViewController navigateTo:url];
[self.inAppBrowserViewController navigateTo:url headers:nil];
}

// This is a helper method for the inject{Script|Style}{Code|File} API calls, which
Expand Down Expand Up @@ -1104,12 +1105,12 @@ - (void)close
});
}

- (void)navigateTo:(NSURL*)url
- (void)navigateTo:(NSURL*)url headers:(NSString*)headers
{
if ([url.scheme isEqualToString:@"file"]) {
[self.webView loadFileURL:url allowingReadAccessToURL:url];
} else {
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest* request = [CDVInAppBrowserOptions createRequest:url headers:headers];
[self.webView loadRequest:request];
}
}
Expand Down
3 changes: 2 additions & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ interface InAppBrowser {
* @param options Options for the InAppBrowser. Optional, defaulting to: location=yes.
* 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.
* @param headers Request headers (Optional).
*/
open(url: string, target?: string, options?: string): InAppBrowser;
open(url: string, target?: string, options?: string, headers?: any): InAppBrowser;

onloadstart(type: Event): void;
onloadstop(type: InAppBrowserEvent): void;
Expand Down
25 changes: 23 additions & 2 deletions www/inappbrowser.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,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 @@ -111,9 +111,30 @@
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 e20c12b

Please sign in to comment.