0
# Network & Communication
1
2
HTTP requests, network status monitoring, and in-app browser functionality for connected applications and web-based interactions.
3
4
## Capabilities
5
6
### HTTP Client
7
8
Advanced HTTP client for making secure requests with custom headers, authentication, and SSL configuration.
9
10
```typescript { .api }
11
/**
12
* HTTP response interface
13
*/
14
interface HTTPResponse {
15
/** HTTP status code */
16
status: number;
17
/** Response data (parsed JSON if applicable) */
18
data?: any;
19
/** Response headers */
20
headers: any;
21
/** Request URL */
22
url: string;
23
}
24
25
/**
26
* HTTP class for making network requests
27
*/
28
class HTTP {
29
/**
30
* Set basic authentication credentials
31
* @param username Basic auth username
32
* @param password Basic auth password
33
*/
34
static useBasicAuth(username: string, password: string): void;
35
36
/**
37
* Set global request header
38
* @param header Header name
39
* @param value Header value
40
*/
41
static setHeader(header: string, value: string): void;
42
43
/**
44
* Enable or disable SSL pinning
45
* @param enable Whether to enable SSL pinning
46
*/
47
static enableSSLPinning(enable: boolean): void;
48
49
/**
50
* Accept all SSL certificates (disable validation)
51
* @param allow Whether to accept all certificates
52
*/
53
static acceptAllCerts(allow: boolean): void;
54
55
/**
56
* Validate domain name in SSL certificate
57
* @param validate Whether to validate domain name
58
*/
59
static validateDomainName(validate: boolean): void;
60
61
/**
62
* Make GET request
63
* @param url Request URL
64
* @param parameters URL parameters
65
* @param headers Request headers
66
* @returns Promise resolving to HTTPResponse
67
*/
68
static get(url: string, parameters: any, headers: any): Promise<HTTPResponse>;
69
70
/**
71
* Make POST request
72
* @param url Request URL
73
* @param body Request body
74
* @param headers Request headers
75
* @returns Promise resolving to HTTPResponse
76
*/
77
static post(url: string, body: any, headers: any): Promise<HTTPResponse>;
78
79
/**
80
* Make PUT request
81
* @param url Request URL
82
* @param body Request body
83
* @param headers Request headers
84
* @returns Promise resolving to HTTPResponse
85
*/
86
static put(url: string, body: any, headers: any): Promise<HTTPResponse>;
87
88
/**
89
* Make PATCH request
90
* @param url Request URL
91
* @param body Request body
92
* @param headers Request headers
93
* @returns Promise resolving to HTTPResponse
94
*/
95
static patch(url: string, body: any, headers: any): Promise<HTTPResponse>;
96
97
/**
98
* Make DELETE request
99
* @param url Request URL
100
* @param parameters URL parameters
101
* @param headers Request headers
102
* @returns Promise resolving to HTTPResponse
103
*/
104
static delete(url: string, parameters: any, headers: any): Promise<HTTPResponse>;
105
106
/**
107
* Make HEAD request
108
* @param url Request URL
109
* @param parameters URL parameters
110
* @param headers Request headers
111
* @returns Promise resolving to HTTPResponse
112
*/
113
static head(url: string, parameters: any, headers: any): Promise<HTTPResponse>;
114
115
/**
116
* Upload file via HTTP
117
* @param url Upload URL
118
* @param body Additional form data
119
* @param headers Request headers
120
* @param filePath Local file path to upload
121
* @param name Form field name for file
122
* @returns Promise resolving to upload response
123
*/
124
static uploadFile(url: string, body: any, headers: any, filePath: string, name: string): Promise<any>;
125
126
/**
127
* Download file via HTTP
128
* @param url Download URL
129
* @param body Request body
130
* @param headers Request headers
131
* @param filePath Local file path to save to
132
* @returns Promise resolving to download result
133
*/
134
static downloadFile(url: string, body: any, headers: any, filePath: string): Promise<any>;
135
}
136
```
137
138
**Usage Examples:**
139
140
```typescript
141
import { HTTP } from 'ionic-native';
142
143
// Configure HTTP client
144
function configureHTTP() {
145
// Set global headers
146
HTTP.setHeader('Content-Type', 'application/json');
147
HTTP.setHeader('User-Agent', 'MyApp/1.0');
148
149
// Configure SSL settings
150
HTTP.enableSSLPinning(false);
151
HTTP.acceptAllCerts(true);
152
HTTP.validateDomainName(true);
153
}
154
155
// GET request with parameters
156
async function fetchUser(userId: string) {
157
try {
158
const response = await HTTP.get(
159
'https://api.example.com/users',
160
{ id: userId },
161
{ 'Authorization': 'Bearer your-token' }
162
);
163
164
console.log('User data:', response.data);
165
return response.data;
166
} catch (error) {
167
console.error('Failed to fetch user:', error);
168
throw error;
169
}
170
}
171
172
// POST request with JSON body
173
async function createUser(userData: any) {
174
try {
175
const response = await HTTP.post(
176
'https://api.example.com/users',
177
userData,
178
{
179
'Authorization': 'Bearer your-token',
180
'Content-Type': 'application/json'
181
}
182
);
183
184
if (response.status === 201) {
185
console.log('User created:', response.data);
186
return response.data;
187
}
188
} catch (error) {
189
console.error('Failed to create user:', error);
190
throw error;
191
}
192
}
193
194
// File upload with progress monitoring
195
async function uploadProfileImage(filePath: string, userId: string) {
196
try {
197
const result = await HTTP.uploadFile(
198
'https://api.example.com/users/avatar',
199
{ userId },
200
{ 'Authorization': 'Bearer your-token' },
201
filePath,
202
'avatar'
203
);
204
205
console.log('Image uploaded successfully:', result);
206
return result;
207
} catch (error) {
208
console.error('Failed to upload image:', error);
209
throw error;
210
}
211
}
212
213
// File download
214
async function downloadDocument(documentId: string, localPath: string) {
215
try {
216
await HTTP.downloadFile(
217
`https://api.example.com/documents/${documentId}/download`,
218
{},
219
{ 'Authorization': 'Bearer your-token' },
220
localPath
221
);
222
223
console.log('Document downloaded to:', localPath);
224
} catch (error) {
225
console.error('Failed to download document:', error);
226
throw error;
227
}
228
}
229
230
// Authentication with basic auth
231
async function authenticateUser(username: string, password: string) {
232
HTTP.useBasicAuth(username, password);
233
234
try {
235
const response = await HTTP.post(
236
'https://api.example.com/auth/login',
237
{},
238
{}
239
);
240
241
return response.data.token;
242
} catch (error) {
243
console.error('Authentication failed:', error);
244
throw error;
245
}
246
}
247
```
248
249
### Network Information
250
251
Monitor network connection status and connection type for handling offline scenarios.
252
253
```typescript { .api }
254
/**
255
* Network class for monitoring connection status
256
*/
257
class Network {
258
/** Current connection type (wifi, cellular, ethernet, none, etc.) */
259
static type: string;
260
261
/** Maximum downlink speed in Mbps */
262
static downlinkMax: number;
263
264
/**
265
* Observable for network connection events
266
* @returns Observable emitting connection events
267
*/
268
static onConnect(): Observable<any>;
269
270
/**
271
* Observable for network disconnection events
272
* @returns Observable emitting disconnection events
273
*/
274
static onDisconnect(): Observable<any>;
275
}
276
277
/**
278
* Connection type constants
279
*/
280
interface Connection {
281
/** Unknown connection */
282
UNKNOWN: 'unknown';
283
/** Ethernet connection */
284
ETHERNET: 'ethernet';
285
/** WiFi connection */
286
WIFI: 'wifi';
287
/** 2G cellular connection */
288
CELL_2G: '2g';
289
/** 3G cellular connection */
290
CELL_3G: '3g';
291
/** 4G cellular connection */
292
CELL_4G: '4g';
293
/** Cellular connection */
294
CELL: 'cellular';
295
/** No network connection */
296
NONE: 'none';
297
}
298
```
299
300
**Usage Examples:**
301
302
```typescript
303
import { Network } from 'ionic-native';
304
305
// Check current network status
306
function checkNetworkStatus() {
307
console.log('Connection type:', Network.type);
308
console.log('Downlink max:', Network.downlinkMax);
309
310
switch (Network.type) {
311
case 'wifi':
312
console.log('Connected to WiFi');
313
break;
314
case 'cellular':
315
console.log('Connected to cellular network');
316
break;
317
case 'none':
318
console.log('No network connection');
319
break;
320
default:
321
console.log('Connection type:', Network.type);
322
}
323
}
324
325
// Monitor network changes
326
function setupNetworkMonitoring() {
327
// Listen for connection events
328
Network.onConnect().subscribe(() => {
329
console.log('Network connected');
330
console.log('New connection type:', Network.type);
331
332
// Sync offline data when reconnected
333
syncOfflineData();
334
});
335
336
// Listen for disconnection events
337
Network.onDisconnect().subscribe(() => {
338
console.log('Network disconnected');
339
340
// Switch to offline mode
341
handleOfflineMode();
342
});
343
}
344
345
// Handle offline functionality
346
function handleOfflineMode() {
347
console.log('Switching to offline mode');
348
349
// Show offline indicator
350
showOfflineIndicator();
351
352
// Queue operations for later sync
353
enableOfflineQueue();
354
}
355
356
// Sync data when coming back online
357
async function syncOfflineData() {
358
console.log('Syncing offline data');
359
360
try {
361
// Upload queued operations
362
await uploadQueuedOperations();
363
364
// Download latest data
365
await downloadLatestData();
366
367
console.log('Sync completed');
368
hideOfflineIndicator();
369
} catch (error) {
370
console.error('Sync failed:', error);
371
}
372
}
373
374
// Network-aware API calls
375
async function makeNetworkAwareRequest(url: string, data: any) {
376
if (Network.type === 'none') {
377
// Queue for later when network is available
378
queueForLaterSync(url, data);
379
return Promise.reject(new Error('No network connection'));
380
}
381
382
try {
383
// Make request based on connection type
384
if (Network.type === 'wifi') {
385
// Full quality for WiFi
386
return await makeRequest(url, data, { quality: 'high' });
387
} else if (Network.type.includes('cellular')) {
388
// Reduced quality for cellular
389
return await makeRequest(url, data, { quality: 'medium' });
390
}
391
} catch (error) {
392
// Queue for retry on network error
393
queueForLaterSync(url, data);
394
throw error;
395
}
396
}
397
```
398
399
### In-App Browser
400
401
Open web content within the app with full browser functionality and communication between app and web content.
402
403
```typescript { .api }
404
/**
405
* In-App Browser event
406
*/
407
interface InAppBrowserEvent {
408
/** Event type (loadstart, loadstop, loaderror, exit) */
409
type: string;
410
/** Event URL */
411
url: string;
412
/** Error code (for loaderror events) */
413
code?: number;
414
/** Error message (for loaderror events) */
415
message?: string;
416
}
417
418
/**
419
* In-App Browser configuration options
420
*/
421
interface InAppBrowserOptions {
422
/** Location bar visibility (yes/no) */
423
location?: 'yes' | 'no';
424
/** Hidden browser (yes/no) */
425
hidden?: 'yes' | 'no';
426
/** Clear browser cache (yes/no) */
427
clearcache?: 'yes' | 'no';
428
/** Clear session cache (yes/no) */
429
clearsessioncache?: 'yes' | 'no';
430
/** Zoom controls (yes/no) */
431
zoom?: 'yes' | 'no';
432
/** Hardware back button (yes/no) */
433
hardwareback?: 'yes' | 'no';
434
/** Media playback requires user action (yes/no) */
435
mediaPlaybackRequiresUserAction?: 'yes' | 'no';
436
/** Should pause on suspend (yes/no) */
437
shouldPauseOnSuspend?: 'yes' | 'no';
438
/** User agent string */
439
useragent?: string;
440
/** Close button caption */
441
closebuttoncaption?: string;
442
/** Close button color */
443
closebuttoncolor?: string;
444
/** Left-to-right layout (yes/no) */
445
lefttoright?: 'yes' | 'no';
446
/** Toolbar visibility (yes/no) */
447
toolbar?: 'yes' | 'no';
448
/** Navigation buttons visibility (yes/no) */
449
navigationbuttoncolor?: string;
450
/** Toolbar color */
451
toolbarcolor?: string;
452
/** Toolbar translucency (yes/no) */
453
toolbartranslucent?: 'yes' | 'no';
454
/** Toolbar position (top/bottom) */
455
toolbarposition?: 'top' | 'bottom';
456
/** Footer visibility (yes/no) */
457
footer?: 'yes' | 'no';
458
/** Footer color */
459
footercolor?: string;
460
/** Presentation style (pagesheet/formsheet/fullscreen) */
461
presentationstyle?: 'pagesheet' | 'formsheet' | 'fullscreen';
462
/** Transition style (fliphorizontal/crossdissolve/coververtical) */
463
transitionstyle?: 'fliphorizontal' | 'crossdissolve' | 'coververtical';
464
}
465
466
/**
467
* In-App Browser object for controlling browser instance
468
*/
469
interface InAppBrowserObject {
470
/**
471
* Show the browser (if hidden)
472
*/
473
show(): void;
474
475
/**
476
* Close the browser
477
*/
478
close(): void;
479
480
/**
481
* Hide the browser
482
*/
483
hide(): void;
484
485
/**
486
* Execute JavaScript in the browser context
487
* @param script Script object with code or file
488
* @returns Promise resolving to script result
489
*/
490
executeScript(script: { code?: string; file?: string; }): Promise<any>;
491
492
/**
493
* Insert CSS into the browser
494
* @param css CSS object with code or file
495
* @returns Promise indicating insertion completion
496
*/
497
insertCSS(css: { code?: string; file?: string; }): Promise<any>;
498
499
/**
500
* Subscribe to browser events
501
* @param event Event name (loadstart, loadstop, loaderror, exit)
502
* @returns Observable emitting InAppBrowserEvent objects
503
*/
504
on(event: string): Observable<InAppBrowserEvent>;
505
}
506
507
/**
508
* InAppBrowser class for opening web content
509
*/
510
class InAppBrowser {
511
/**
512
* Open URL in in-app browser
513
* @param url URL to open
514
* @param target Target (_blank, _self, _system)
515
* @param options Browser configuration options
516
* @returns InAppBrowserObject instance
517
*/
518
static create(url: string, target?: string, options?: string | InAppBrowserOptions): InAppBrowserObject;
519
}
520
```
521
522
**Usage Examples:**
523
524
```typescript
525
import { InAppBrowser, InAppBrowserObject, InAppBrowserOptions } from 'ionic-native';
526
527
// Open web page with custom options
528
function openWebPage(url: string) {
529
const options: InAppBrowserOptions = {
530
location: 'yes',
531
hidden: 'no',
532
clearcache: 'yes',
533
clearsessioncache: 'yes',
534
zoom: 'yes',
535
hardwareback: 'yes',
536
mediaPlaybackRequiresUserAction: 'no',
537
shouldPauseOnSuspend: 'no',
538
closebuttoncaption: 'Close',
539
closebuttoncolor: '#0000ff',
540
toolbar: 'yes',
541
toolbarcolor: '#f0f0f0',
542
toolbarposition: 'top'
543
};
544
545
const browser = InAppBrowser.create(url, '_blank', options);
546
547
// Handle browser events
548
browser.on('loadstart').subscribe(event => {
549
console.log('Loading started:', event.url);
550
});
551
552
browser.on('loadstop').subscribe(event => {
553
console.log('Loading finished:', event.url);
554
555
// Inject custom CSS
556
browser.insertCSS({
557
code: `
558
body {
559
background-color: #f5f5f5;
560
font-family: Arial, sans-serif;
561
}
562
`
563
});
564
565
// Execute custom JavaScript
566
browser.executeScript({
567
code: `
568
document.addEventListener('DOMContentLoaded', function() {
569
console.log('Page loaded in InAppBrowser');
570
});
571
`
572
});
573
});
574
575
browser.on('loaderror').subscribe(event => {
576
console.error('Loading error:', event.message);
577
});
578
579
browser.on('exit').subscribe(event => {
580
console.log('Browser closed');
581
});
582
583
return browser;
584
}
585
586
// Open payment gateway
587
function openPaymentGateway(paymentUrl: string, amount: number) {
588
const options: InAppBrowserOptions = {
589
location: 'no',
590
toolbar: 'no',
591
zoom: 'no',
592
hardwareback: 'no',
593
clearcache: 'yes',
594
clearsessioncache: 'yes'
595
};
596
597
const browser = InAppBrowser.create(paymentUrl, '_blank', options);
598
599
return new Promise((resolve, reject) => {
600
browser.on('loadstop').subscribe(event => {
601
// Check if payment is completed
602
browser.executeScript({
603
code: 'window.location.href'
604
}).then(result => {
605
const currentUrl = result[0];
606
607
if (currentUrl.includes('payment-success')) {
608
browser.close();
609
resolve({ success: true, amount });
610
} else if (currentUrl.includes('payment-failed')) {
611
browser.close();
612
reject(new Error('Payment failed'));
613
}
614
});
615
});
616
617
browser.on('exit').subscribe(() => {
618
reject(new Error('Payment cancelled'));
619
});
620
});
621
}
622
623
// Social login with OAuth
624
function socialLogin(provider: string) {
625
const authUrl = `https://auth.example.com/oauth/${provider}`;
626
const redirectUrl = 'https://myapp.com/auth/callback';
627
628
const options: InAppBrowserOptions = {
629
location: 'yes',
630
clearcache: 'yes',
631
toolbar: 'yes',
632
closebuttoncaption: 'Cancel'
633
};
634
635
const browser = InAppBrowser.create(authUrl, '_blank', options);
636
637
return new Promise((resolve, reject) => {
638
browser.on('loadstart').subscribe(event => {
639
if (event.url.startsWith(redirectUrl)) {
640
// Parse OAuth callback URL
641
const url = new URL(event.url);
642
const code = url.searchParams.get('code');
643
const error = url.searchParams.get('error');
644
645
browser.close();
646
647
if (code) {
648
resolve({ code, provider });
649
} else if (error) {
650
reject(new Error(`OAuth error: ${error}`));
651
}
652
}
653
});
654
655
browser.on('exit').subscribe(() => {
656
reject(new Error('Login cancelled'));
657
});
658
});
659
}
660
661
// Help and documentation viewer
662
function openHelpDocs(section?: string) {
663
const baseUrl = 'https://docs.myapp.com';
664
const url = section ? `${baseUrl}/${section}` : baseUrl;
665
666
const options: InAppBrowserOptions = {
667
location: 'no',
668
toolbar: 'yes',
669
toolbarcolor: '#2196F3',
670
toolbarposition: 'top',
671
closebuttoncaption: 'Done',
672
zoom: 'yes',
673
hardwareback: 'yes'
674
};
675
676
const browser = InAppBrowser.create(url, '_blank', options);
677
678
// Add custom navigation
679
browser.on('loadstop').subscribe(() => {
680
browser.executeScript({
681
code: `
682
// Add back to app button
683
const backButton = document.createElement('button');
684
backButton.innerText = 'Back to App';
685
backButton.style.position = 'fixed';
686
backButton.style.top = '10px';
687
backButton.style.right = '10px';
688
backButton.style.zIndex = '9999';
689
backButton.onclick = function() {
690
window.location.href = 'close://';
691
};
692
document.body.appendChild(backButton);
693
`
694
});
695
});
696
697
browser.on('loadstart').subscribe(event => {
698
if (event.url === 'close://') {
699
browser.close();
700
}
701
});
702
703
return browser;
704
}
705
```