1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
|
/*
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.
*/
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
#if WP8
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Storage;
using Windows.System;
//Use alias in case Cordova File Plugin is enabled. Then the File class will be declared in both and error will occur.
using IOFile = System.IO.File;
#else
using Microsoft.Phone.Tasks;
#endif
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;}
protected string NavigationCallbackId { 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];
this.NavigationCallbackId = args[3];
if (!string.IsNullOrEmpty(featString))
{
string[] features = featString.Split(',');
foreach (string str in features)
{
try
{
string[] split = str.Split('=');
switch (split[0])
{
case "location":
ShowLocation = split[1].StartsWith("yes", StringComparison.OrdinalIgnoreCase);
break;
case "hidden":
StartHidden = split[1].StartsWith("yes", StringComparison.OrdinalIgnoreCase);
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 cordova-plugin-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 cordova-plugin-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 cordova-plugin-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.Navigate2(loc);
}
}
}
});
}
#if WP8
private async void ShowSystemBrowser(string url)
{
var pathUri = new Uri(url, UriKind.Absolute);
if (pathUri.Scheme == Uri.UriSchemeHttp || pathUri.Scheme == Uri.UriSchemeHttps)
{
await Launcher.LaunchUriAsync(pathUri);
return;
}
var file = await GetFile(pathUri.AbsolutePath.Replace('/', Path.DirectorySeparatorChar));
if (file != null)
{
await Launcher.LaunchFileAsync(file);
}
else
{
Debug.WriteLine("File not found.");
}
}
private async Task<StorageFile> GetFile(string fileName)
{
//first try to get the file from the isolated storage
var localFolder = ApplicationData.Current.LocalFolder;
if (IOFile.Exists(Path.Combine(localFolder.Path, fileName)))
{
return await localFolder.GetFileAsync(fileName);
}
//if file is not found try to get it from the xap
var filePath = Path.Combine(Package.Current.InstalledLocation.Path, fileName);
if (IOFile.Exists(filePath))
{
return await StorageFile.GetFileFromPathAsync(filePath);
}
return null;
}
#else
private void ShowSystemBrowser(string url)
{
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri(url, UriKind.Absolute);
webBrowserTask.Show();
}
#endif
private void ShowInAppBrowser(string url)
{
Uri loc = new Uri(url, UriKind.RelativeOrAbsolute);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (browser != null)
{
//browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
browser.Navigate2(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.Navigate2(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;
page.BackKeyPress += page_BackKeyPress;
}
}
}
});
}
void page_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
#if WP8
if (browser.CanGoBack)
{
browser.GoBack();
}
else
{
close();
}
e.Cancel = true;
#else
browser.InvokeScript("execScript", "history.back();");
#endif
}
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;
page.BackKeyPress -= page_BackKeyPress;
}
}
browser = null;
string message = "{\"type\":\"exit\"}";
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
result.KeepCallback = false;
this.DispatchCommandResult(result, NavigationCallbackId);
});
}
}
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, NavigationCallbackId);
}
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, NavigationCallbackId);
}
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, NavigationCallbackId);
}
}
internal static class WebBrowserExtensions
{
/// <summary>
/// Improved method to initiate request to the provided URI. Supports 'data:text/html' urls.
/// </summary>
/// <param name="browser">The browser instance</param>
/// <param name="uri">The requested uri</param>
internal static void Navigate2(this WebBrowser browser, Uri uri)
{
// IE10 does not support data uri so we use NavigateToString method instead
if (uri.Scheme == "data")
{
// we should remove the scheme identifier and unescape the uri
string uriString = Uri.UnescapeDataString(uri.AbsoluteUri);
// format is 'data:text/html, ...'
string html = new System.Text.RegularExpressions.Regex("^data:text/html,").Replace(uriString, "");
browser.NavigateToString(html);
}
else
{
browser.Navigate(uri);
}
}
}
}
|