Compare commits

...

222 Commits

Author SHA1 Message Date
Niklas Merz
d2b512ed04 Updated version and RELEASENOTES.md for release 4.0.0 (cordova-plugin-inappbrowser-4.0.0) 2020-06-09 18:54:58 +02:00
Niklas Merz
090345248c (ios): fix regression in 2706f34 (#715)
Fix merging issue from #656

Closes #714
2020-06-05 15:23:10 +02:00
jcesarmobile
04ce789724 chore: update install engines (#685) 2020-06-04 16:48:03 +02:00
PDLMobileApps
2706f3460d (ios) Remove fake status bar with hardcoded height to fix issues in iOS devices with a notch (#656)
* (ios) Removed fake statusbar with hardcoded height to fix issues in iOS devices with a notch

* (ios) Removed no longer needed bgToolbar

* (ios) Fixed issue with rotation in landscape mode and refactored/simplified the code

Co-authored-by: Alessandro Basso <Alessandro.Basso@PeapodDigitalLabs.com>
2020-06-04 16:32:07 +02:00
Dani Palou
dcfe692ccd fix(ios): Allow loading local html files (#693) 2020-05-17 00:24:36 +02:00
Nicolas HENRY
8aaae5b3f7 GH-292 android: SSL errors handling in Android (#293) 2020-05-08 12:02:39 +00:00
jcesarmobile
2793e16ab4 fix(ios): prevent statusbar rotation after closing InAppBrowser (#672) 2020-04-27 17:54:02 +02:00
Erisu
cbe345689b chore(asf): update git notification settings 2020-04-22 13:41:11 +09:00
csware
9b6b229509 Allow App using inappbrowser to be hosted in a cross-origin ifra… (#669)
Signed-off-by: Sven Strickroth <email@cs-ware.de>
2020-04-14 17:22:08 +00:00
Niklas Merz
074d4d03ea (all platforms): remove "window.open" overwrite (#600)
Closes #599
2020-04-14 15:25:54 +02:00
Tim Brust
548f19ca90 chore: bump version to 4.0.0-dev (#670) 2020-04-14 12:56:53 +00:00
Niklas Merz
4227fe8211 Update CONTRIBUTING.md 2020-04-13 14:29:50 +02:00
Tim Brust
df4615dea4 docs: replaces outdated transition and presentation style links (#662) 2020-04-07 13:20:36 +00:00
jcesarmobile
396c085ba3 chore: remove deprecated orientation methods (#666) 2020-04-06 15:21:22 +02:00
Kamil Burek
c01f037c8a Fix incorrect TypeScript typings (#515)
* fix #514

* Update based on conversation in #514

* Fixed whitespace
2020-04-03 12:08:32 +00:00
Jim Wright
11ba4c4e7e [GH-652] add check for openInSystem postNotification (#654)
Co-authored-by: Jim Wright <jim.wright@masabi.com>
2020-03-30 10:47:30 +00:00
Tim Brust
7a856bec60 ci: updates Node.js versions (#659) 2020-03-27 18:24:32 +00:00
Tim Brust
4129f11e24 chore(npm): improve ignore list (#658) 2020-03-27 18:24:22 +00:00
Jesse MacFadyen
290841dea6 fix(android): Reset lefttoright if not set (#442)
This fixes #441
2020-03-25 18:08:04 +00:00
Mosab A
0e5f05c938 [android] Correcting the documentation regarding lefttoright opt… (#648) 2020-03-25 17:18:41 +00:00
PDLMobileApps
e78ffe7fc2 (android) Added option to turn on/off fullscreen mode in Android (#634)
* (android) Added option to turn on/off fullscreen mode in Android

* (android) Reverted version changes as requested

* (android) Changing default option value to enabled as per request

Co-authored-by: Alessandro Basso <Alessandro.Basso@PeapodDigitalLabs.com>
2020-03-24 13:24:14 +00:00
Slayterik
e658c8c201 Android GH-470 InAppBrowser: java.lang.IllegalArgumentException (#616)
Fix interacting with views when Activity destroyed
Bug description https://stackoverflow.com/questions/22924825/view-not-attached-to-window-manager-crash

Co-authored-by: Sarafanov Valeriy <sarafanov_v@firma-gamma.ru>
2020-03-20 14:07:48 +00:00
jcesarmobile
6c55e6172c breaking(ios): remove UIWebView (#635) 2020-03-05 15:51:31 +01:00
Niklas Merz
09ad59f7ef chore(release): 3.2.1-dev 2020-01-06 07:23:15 +01:00
Niklas Merz
81aa8ba5a9 (ios) fix regression in injectScriptFile
Fixes issue introduced in #584
2020-01-06 07:20:07 +01:00
Niklas Merz
2cd868e99f chore(release): release notes for 3.2.0 2020-01-04 09:43:11 +01:00
Niklas Merz
6aca3f7fb4 chore(release): 3.2.0 (version string) 2020-01-04 09:24:36 +01:00
Niklas Merz
7b42f3e105 Merge pull request #503 from alexyazvinsky/def-fix
(android) Defensive code to prevent NULL reference exceptions for async
2020-01-04 08:57:52 +01:00
Maik Hummel
82bbe29986 (ios) add compile-time decision for disabling UIWebView (#584) 2020-01-04 08:55:28 +01:00
Niklas Merz
785fc4c83d chore(release): 3.2.0-dev 2020-01-02 21:27:59 +01:00
Niklas Merz
d4338bd64a (android) improve defensive code for NULL check 2020-01-02 19:53:36 +01:00
Alex Yaz
0411a287b8 (android) defensive code to prevent NULL reference exceptions for async
Signed-off-by: Niklas Merz <niklasmerz@apache.org>
2020-01-02 19:50:26 +01:00
Lorenzo B
416b05c1e5 Replace "beforeload" with BEFORELOAD (#524)
Improve code formatting
2019-12-30 10:47:37 +01:00
mosababubakr
9a15737577 Update missing closed brace to the insert.CSS (#568) 2019-11-04 15:23:44 +00:00
Norman Breau
7b6f95964a Merge pull request #567 from mosababubakr/patch-1
Update missing closed brace to the insert.CSS
2019-11-03 11:09:54 -04:00
mosababubakr
1e16c50b1a Update missing closed brace to the insert.CSS 2019-11-03 16:56:59 +02:00
Dave Alden
80feff6cf8 Merge pull request #401 from GEDYSIntraWare/bridge
Move bridge creation to injectDeferredObject
2019-09-24 16:21:19 +01:00
Dave Alden
ba345b0159 Merge pull request #534 from GEDYSIntraWare/fix-show-ios13
Fix inappbrowser not opening on iOS 13 by using reusable window. Resolves #492
2019-09-24 15:43:48 +01:00
Niklas Merz
855394628e Fix unresponsive main window after hide 2019-09-24 16:28:07 +02:00
Niklas Merz
79b1bb61a0 Move window hiding to 'browserExit'
Fixes close, hide and toolbar 'done' and makes cordova window responsive
2019-09-23 10:29:31 +02:00
Niklas Merz
4376ddabcd New fix attempt 2019-09-20 15:48:27 +02:00
Niklas Merz
82d496ae5c Use tmpWindow and hide on close 2019-09-20 13:43:57 +02:00
Niklas Merz
81bec09526 (ios) Fix iOS 13 show not working
Removed tmpWindow and controller.
This was introduced to fix IAB with WKWebView before WKIAB existed.
2019-09-06 14:14:51 +02:00
Niklas Merz
8805f5d46a Finish revert and correct Xcode warnings 2019-09-06 13:53:36 +02:00
Niklas Merz
8810c6a8a0 (ios) Fix inappbrowser not opening on iOS 13 by using reusable window
Closes #492
2019-09-06 13:49:44 +02:00
Jan Piotrowski
2b59941514 ci(travis): upgrade to node8 2019-07-01 20:26:57 +02:00
Jan Piotrowski
84dfb09edd chore(release): 3.1.1-dev 2019-06-28 23:12:38 +02:00
Jan Piotrowski
df623882c2 chore(release): 3.1.0 (version string) 2019-06-28 23:12:38 +02:00
Jan Piotrowski
b84203970f chore(release): release notes for 3.1.0 2019-06-28 23:12:38 +02:00
Jan Piotrowski
e9dad636d2 chore: fix repo and issue urls and license in package.json and plugin.xml 2019-06-28 23:12:38 +02:00
Jan Piotrowski
f3b695fde5 build: add .npmignore to remove unneeded files from npm package 2019-06-28 23:12:38 +02:00
Jan Piotrowski
5741d4af6d build: add .gitattributes to force LF (instead of possible CRLF on Windows) 2019-06-28 23:12:38 +02:00
Jan Piotrowski
c2bb6c1409 ci(travis): Update Travis CI configuration for new paramedic (#478)
* Update Travis CI configuration for new paramedic

* remove wrong ADDITIONAL_TESTS_DIR

* Update .travis.yml

* remove failing platform
2019-06-20 15:19:13 +02:00
Jan Piotrowski
cc5ee007c6 docs: remove outdated translations 2019-06-20 15:18:42 +02:00
Ralph Gutkowski
94fec84d5c Fix beforeload for Android <= 7 (#427)
* Fix beforeload for Android <= 7
* Change Android version check conditional
2019-06-13 00:33:23 +05:30
Jesse MacFadyen
a162bd9076 Fix failing CI tests (#460)
* bump node version to 6
* use default travis osx_image of xcode9.4
* comment out flakey local test
2019-04-09 10:49:41 -07:00
Jesse MacFadyen
af44235a61 Merge pull request #440 from cordova-develop/fix-close-event-test
Fix test spec.5 to close inappbrowser after loadstop event
2019-03-06 00:00:48 -08:00
Jesse MacFadyen
2500b08946 Merge pull request #383 from cvanem/master
Example documentation - Fix messageCallBack and beforeloadCallBack function names
2019-03-05 23:55:34 -08:00
Jesse MacFadyen
d01bd25a88 Merge pull request #262 from landsbankinn/CB-13969
Cb 13969 - Allow close button and navigation buttons positions to be swapped
2019-03-05 23:31:12 -08:00
Jesse MacFadyen
eb3acc04cc Merge pull request #439 from apache/revert-353-patch-1
Revert "Add support for right to left direction languages"
I mistakenly merged #353 instead of a similar one.
2019-03-05 23:27:13 -08:00
KNaito
5f1afbdf05 Fix test spec.5 to close inappbrowser after loadstop event 2019-03-06 11:47:21 +09:00
Jesse MacFadyen
2f74d677b7 Revert "Add support for right to left direction languages" 2019-03-05 17:56:34 -08:00
Jesse MacFadyen
7b16ee88a4 Merge pull request #353 from transoceanic/patch-1
Add support for right to left direction languages
2019-03-05 17:34:19 -08:00
Jesse MacFadyen
c95dbcbaea Merge pull request #436 from purplecabbage/ValidateCallbackId
[android] Prevent malformed callbackId from reaching app cordova view
2019-03-01 20:54:49 -08:00
Jesse MacFadyen
686108484e Prevent malformed callbackId from reaching app cordova view 2019-02-28 14:52:01 -08:00
Steinar Ágúst
f861655382 CB-13969 fixing README to be correct for lefttoright option 2019-02-28 15:17:24 +00:00
Steinar Ágúst
9c7c2f31d8 CB-13969 functionality extended to WKWebView 2019-02-28 14:39:26 +00:00
steinaragustli
3c0a42e2ae CB-13969 fix inappbrowser.css to be unmodified 2019-02-28 14:11:04 +00:00
Steinar Ágúst
5359f6cf18 CB-13969 reverting to older version of inappbrowser.css to leave it out of PR 2019-02-28 14:05:05 +00:00
Steinar Á. Steinarsson
df84ddabd2 CB-13969 trying to fix some wierd issue for PR 2019-02-28 13:04:21 +00:00
Steinar Á. Steinarsson
2bcec40213 CB-13969 trying to fix some wierd issue for PR 2019-02-28 13:02:04 +00:00
steinaragustli
fc0c560bff CB-13969 trying to remove inappbrowser from pr 2019-02-28 12:50:53 +00:00
steinaragustli
5ead1e6a7e CB-13969 trying to remove inappbrowser.css from pr 2019-02-28 12:50:02 +00:00
Steinar Ágúst
c7931faa7e CB-13969 adding newline at end of inappbrowser.cs 2019-02-28 12:36:28 +00:00
Steinar Ágúst
e2adf1b285 CB-13969 fixing inappbrowser.css 2019-02-28 12:33:15 +00:00
Steinar Ágúst
4adf4c7230 CB-13969 updating README.MD to better explain lefttoright parameter option, reverting unneccesary indent changes on inappbrowser.css 2019-02-28 12:28:58 +00:00
Steinar Ágúst
74ccef1226 Merge remote-tracking branch 'upstream/master' 2019-02-28 11:43:34 +00:00
Jan Piotrowski
92243cdcc2 Add headline to window.open documentation (#406) 2019-02-22 18:27:30 +01:00
Dave Alden
388e3f6ae7 (iOS) Fix iframes in iOS/WKWebView which were broken by #418. Fixes #424. (#425) 2019-02-12 00:14:18 +01:00
Jan Piotrowski
ae329bc4c2 Add or update GitHub pull request and issue template 2019-02-11 18:39:42 +01:00
Dave Alden
9f4b72982a GH-417: Handle non-default target attribute values (e.g. target=on links in WKWebView implementation on iOS (#418) 2019-02-10 18:06:35 +01:00
Tim Brust
6db2f2d324 fix(typescript): remove unused replace parameter (#410)
This closes #295
2019-01-29 22:54:54 +01:00
Niklas Merz
e3db974080 (ios) Move createIframeBridge to injectDeferredObject
Avoid failed script injections for pages which did not finish loading.
2019-01-16 14:22:51 +01:00
cvanem
a890e606eb Example documentation - Fix callBack function name 2018-12-25 15:01:43 -07:00
Dave Alden
632a395b3d GH-359: Fix beforeload to work with POST requests (#367)
### Platforms affected
iOS and Android


### What does this PR do?
Fixes the behaviour of `beforeload` to resolve the problem with POST requests outlined in #359.

The `beforeload` parameter has been changed from taking only a boolean (`yes` or not defined) to a discrete string with possible values of `get`, `post`, or `yes` which correspond to request types of GET, POST or GET&POST respectively. The `README.md` has been updated to reflect this.

Note that use of `beforeload` to intercept POST requests is currently not supported on Android or iOS, so if `beforeload=yes` is specified and a POST request is detected as the HTTP request method, `beforeload` behaviour will not be applied. If `beforeload=post` is specified, a `loaderror` event will be dispatched which states that POST requests are not yet supported.

#### Notes for Android

The `shouldOverrideUrlLoading()` override method has been updated to support the [new method interface added in API 24 / Android 7][1] which receives the `WebResourceRequest` instead of just the `String url`, enabling the HTTP method of the request to be determined. The [deprecated method interface][2] has also been preserved for API <=23, but in this case the HTTP method cannot be determined so is passed as null.

Also note that due to a [Chromium bug](https://bugs.chromium.org/p/chromium/issues/detail?id=155250),  `shouldOverrideUrlLoading()` is currently not called for POST requests. It's possible this may be resolved in a future Chromium version in the Android System Webview (given that this is now self-updating and independent of Android version since Android 5.0) - in prospective anticipation of this, code to handle POST requests has been added to `shouldOverrideUrlLoading()`.

However, it seems more likely that this won't be resolved any time soon given that [a Chromium dev said](https://bugs.chromium.org/p/chromium/issues/detail?id=155250#c39):

 > We're looking at implementing a better way to handle request interception in a future OS version. There's no way to just "fix" this, the API doesn't accommodate this usage at all. This will not be something you can use any time soon.

Therefore if we want to go ahead and use `beforeload` to intercept request types other than GET, it's likely we'll instead need to use the `shouldInterceptRequest()` method override. As with `shouldOverrideUrlLoading()`, there are a two variants: the [new method interface][3] added in API 21 / Android 5.0 which  which receives the `WebResourceRequest` object and the [deprecated one][4] which receives only `String url`. If we want to determine the HTTP request method, we'll need to use the new implementation. This has been empirically tested and *is* called for POST requests so would allow the possibility to intercept, delay, modify and send the POST request and its data via `beforeload`.
Both `shouldInterceptRequest()` method interfaces have been exposed in the Android implentation for potential future use but they currently do nothing other than return the unadulterated request object.

### What testing has been done on this change?
Manual testing of POST and GET requests on both platforms using a test app container:
https://github.com/dpa99c/cordova-plugin-inappbrowser-test

[1]: https://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading(android.webkit.WebView,%20android.webkit.WebResourceRequest)
[2]: https://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading(android.webkit.WebView,%20java.lang.String)
[3]: https://developer.android.com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest(android.webkit.WebView,%20android.webkit.WebResourceRequest)
[4]: https://developer.android.com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest(android.webkit.WebView,%20java.lang.String)
2018-12-20 20:31:14 +01:00
Dave Alden
c54d10052a (iOS & Android) Add postMessage API support (#362)
<!--
Please make sure the checklist boxes are all checked before submitting the PR. The checklist
is intended as a quick reference, for complete details please see our Contributor Guidelines:

http://cordova.apache.org/contribute/contribute_guidelines.html

Thanks!
-->

### Platforms affected
Android
iOS (both UIWebView & WKWebView implementations)

### What does this PR do?
Adds support for [postMessage API](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) enabling pages loaded into the InappBrowser to post messages back to the parent Webview of the Cordova app.

For example, sending event messages associated with UI interactions such as button clicks from the wrapped page back to the parent app Webview.

### What testing has been done on this change?
Automated tests have been extended to cover the `message` event.

### Checklist
- [x ] Commit message follows the format: "GH-3232: (android) Fix bug with resolving file paths", where CB-xxxx is the JIRA ID & "android" is the platform affected.
- [ x] Added automated test coverage as appropriate for this change.
2018-12-13 17:21:45 +01:00
transoceanic
ba3a440491 Added to support android devices with right to left direction languages (issue #352) 2018-11-22 15:45:34 +02:00
Dave Alden
0fd43ae644 Fixes loadAfterBeforeload on iOS. Resolves #349. (#350)
For both UIWebView and WKWebView implementations on iOS.

<!--
Please make sure the checklist boxes are all checked before submitting the PR. The checklist
is intended as a quick reference, for complete details please see our Contributor Guidelines:

http://cordova.apache.org/contribute/contribute_guidelines.html

Thanks!
-->

### Platforms affected
iOS

### What does this PR do?
Fixes `beforeload` event (introduced by #276) for iOS

### What testing has been done on this change?
Tested both allow & deny loading of URL with both iOS implementations in [test container app](https://github.com/dpa99c/cordova-plugin-inappbrowser-wkwebview-test) (ignore its README).

- To test with UIWebView use options: `beforeload=yes,usewkwebview=no`
- To test with WKWebView use options: `beforeload=yes,usewkwebview=yes`

### Checklist
- [x] [Reported an issue](http://cordova.apache.org/contribute/issues.html) in the JIRA database
- [x] Commit message follows the format: "CB-3232: (android) Fix bug with resolving file paths", where CB-xxxx is the JIRA ID & "android" is the platform affected.
- [x] Added automated test coverage as appropriate for this change.

closes #349
2018-11-21 19:04:04 +01:00
Dave Alden
3b82c160d9 Fix crashes when using WKWebView implementation on iOS 9. (#337)
Fixes #323. Fixes #324.
2018-11-20 17:12:29 +01:00
Jonathan Li
978b147598 Fix iOS CDVWKInAppBrowser evaluateJavascript method randomly gets blocked on ios 12 (#341)
### Platforms affected
iOS

### What does this PR do?
fix issue[ #340](https://github.com/apache/cordova-plugin-inappbrowser/issues/340) iOS CDVWKInAppBrowser evaluateJavascript method randomly gets blocked on iOS 12

### What testing has been done on this change?
manual testing

### Checklist
- [x] [Reported an issue](http://cordova.apache.org/contribute/issues.html) in the JIRA database
- [x] Commit message follows the format: "CB-3232: (android) Fix bug with resolving file paths", where CB-xxxx is the JIRA ID & "android" is the platform affected.
- [ ] Added automated test coverage as appropriate for this change.
2018-11-19 18:28:25 +01:00
Jan Piotrowski
3eadde65ab remove unwanted information in README table (#308)
remove unwanted information in README table
2018-11-06 19:53:54 +01:00
Jesse MacFadyen
27fe8ec8d4 Merge pull request #336 from purplecabbage/windowlevel
This lets the default window layering do it's thing.
2018-10-29 14:01:35 -07:00
Jesse MacFadyen
c24bb46965 This lets the default window layering do it's thing. Fixes #334. Fixes #314. 2018-10-29 13:43:37 -07:00
Jesse MacFadyen
10a06691f9 Merge pull request #271 from dpa99c/CB-7179
CB-7179 (iOS): Add WKWebView support for iOS
2018-10-16 23:08:27 -07:00
Dave Alden
3927b8f2fe Merge branch 'CB-7179' of https://github.com/dpa99c/cordova-plugin-themeablebrowser into CB-7179 2018-10-09 11:58:18 +01:00
Dave Alden
82482158c5 Comment out iOS 9 target for Travis tests since it's not supported by the WKWebView implementation 2018-10-09 11:57:40 +01:00
Dave Alden
61014dd877 Fix indentation of tests.js for eslint 2018-10-09 11:48:15 +01:00
Dave Alden
c41f5b5131 Fix merge error 2018-10-09 11:31:26 +01:00
Dave Alden
19c6dfe197 Merge branch 'master' into CB-7179 2018-10-09 11:15:23 +01:00
Dave Alden
7f5fa2a28f Add plugin to fix reporting of cordova-paramedic results when using WKWebView plugin.
See https://github.com/apache/cordova-paramedic/issues/52
2018-10-09 10:51:06 +01:00
Dave Alden
5d2df218d8 Merge branch 'CB-7179' of https://github.com/dpa99c/cordova-plugin-inappbrowser into CB-7179 2018-10-05 21:24:58 +01:00
Dave Alden
86cc778c4a Fix tests so they auto-start when run via cordova-paramedic 2018-10-05 21:23:56 +01:00
Jan Piotrowski
d9cafcdb14 remove JIRA link 2018-10-04 01:16:19 +02:00
Chris Brody
eafaedaec4 Merge pull request #276 from q-m/feature/beforeload-event
CB-14188: Add beforeload event, catching navigation before it happens
2018-10-03 18:43:59 -04:00
Jan Piotrowski
cbfa195f7d Merge branch 'master' into CB-7179 2018-10-03 17:37:28 +02:00
Jan Piotrowski
52e3534ca7 update test configuration to xcode8.3 2018-10-03 17:34:12 +02:00
Jan Piotrowski
8165232a5a experimental commit 2018-10-03 16:55:12 +02:00
Tim Brust
a0c267fe36 CB-12941: update typings (#267)
### Platforms affected
n/a - development with TypeScript

### What does this PR do?
Updates the typings to match the latest published version on DefinitelyTyped.  
See https://github.com/DefinitelyTyped/DefinitelyTyped/pull/17192 and https://stackoverflow.com/q/42095516/1902598

### What testing has been done on this change?
Project compiles again ;)

### Checklist
- [x] [Reported an issue](http://cordova.apache.org/contribute/issues.html) in the JIRA database
- [x] Commit message follows the format: "CB-3232: (android) Fix bug with resolving file paths", where CB-xxxx is the JIRA ID & "android" is the platform affected.
- n/a: Added automated test coverage as appropriate for this change.

fixes #300
2018-10-02 11:49:11 +02:00
wvengen
228703a63b CB-14188: add beforeload event, catching navigation before it happens 2018-10-01 16:41:21 +02:00
Jan Piotrowski
0ed0bf543b reenable testing on all platforms
was disabled in #277
2018-10-01 12:46:54 +02:00
Jan Piotrowski
f8ad52894b also accept terms for android sdk android-27 2018-10-01 12:36:35 +02:00
Dave Alden
e2210bdbcc Merge branch 'CB-7179' of https://github.com/dpa99c/cordova-plugin-inappbrowser into CB-7179 2018-09-30 13:22:32 +01:00
Dave Alden
dc7fa34bbe CB-7179 (iOS): Add support to optionally use WKWebView for iOS 2018-09-30 10:05:46 +01:00
Dave Alden
b48e02fcd5 fix iOS 10 build 2018-09-30 08:03:16 +01:00
Dave Alden
27e6c67909 CB-7179 (iOS): Add support to optionally use WKWebView for iOS 2018-09-30 07:44:05 +01:00
Dan Polivy
a0783378fc [CB-10795] Exclude current app from external intent list (#154)
On Android, if the app defines an intent-filter for a given URL, and
then tries to use inappbrowser to launch that URL via the _system
target, the default handler for that intent is the app itself.

That behavior can lead to circular loops, and ultimately is not what the
developer wants -- the link should be launched in a browser.

Because there is no easy way to find the "default" system browser on a
device, this solution will do two things:
1) Check if the app is one of the targets for this intent
2) If so, create a custom chooser with all other targets, excluding the
current app.

If the app is not a target, then the current (existing) behavior is
preserved.

The only real "downside" to this approach is that a default handler can no longer be set for these URLs within the app, and a chooser will be shown each time the user taps a link that opens in a new browser.

Fixes https://issues.apache.org/jira/browse/CB-10795
2018-09-20 22:43:52 +02:00
Dan Polivy
cf58b04097 CB-14234: Don't call handleOpenURL for system URLs (#278)
When calling `.open()` with a target of `_system`, the InAppBrowser on iOS is both launching the URL in the system browser AND also broadcasting to open the URL within the app (calling handleOpenURL). The latter behavior is problematic in many circumstances (e.g. when you want to explicitly open a link in a browser which is a universal link handled by the app).

This commit attempts to address this by checking the return value from openURL -- if it does not open the URL successfully, then (and only then) the code falls back to broadcasting the event within the app to handleOpenURL.
2018-08-22 23:43:06 +02:00
Malte Norström
dc5329d157 CB-12875: (iOS) Pushes the inappbrowser window to a higher ui level than the existing apps window. (#284) 2018-08-21 10:28:56 +02:00
Chris Brody
de86501026 Merge pull request #277 from brodybits/quick-ci-fixes
Quick CI fixes
2018-07-31 19:30:46 -04:00
Christopher J. Brody
07d9a9939b Skip Android 6.0 on Travis CI (for now) 2018-07-31 19:18:29 -04:00
Christopher J. Brody
81f1437b6d README.md add AppVeyor CI & Travis CI details 2018-07-31 19:05:28 -04:00
Christopher J. Brody
a464ea6875 .travis.yml quick fixes
- skip some platform versions for now
- mark FUTURE TBD platform versions
2018-07-31 19:04:19 -04:00
Christopher J. Brody
e75fe14c4b .appveyor.yml add npm i & add eslint to test
(consistent with test script in package.json)
2018-07-31 18:57:53 -04:00
Christopher J. Brody
eb245ecaf7 .travis.yml add blank lines 2018-07-31 16:54:01 -04:00
jcesarmobile
9cc7f69625 Merge pull request #272 from jcesarmobile/CB-12922
CB-12922 (ios): fix In-app browser does not cede control
2018-07-12 00:30:32 +02:00
Julio César
dac06aa3f3 CB-12922 (ios): fix In-app browser does not cede control 2018-07-01 18:09:47 +02:00
jcesarmobile
26cf6e488c Merge pull request #269 from timbru31/fix/CB-14061-handle-more-url-schemes
CB-14061: (android) comply with RFC 3986 for custom URL scheme handling
2018-05-19 13:57:13 +02:00
jcesarmobile
33aff11f45 Merge pull request #268 from wtrocki/CB-14048
CB-14048: (android) allowedSchemes check empty string fix
2018-05-19 13:49:36 +02:00
Tim Brust
f57ede9be2 CB-14061: (android) comply with RFC 3986 for custom URL scheme handling 2018-05-02 20:18:34 +02:00
Wojciech Trocki
57eda786e0 CB-14048: (android) allowedSchemes check empty string fix 2018-04-27 00:07:57 +01:00
Fiffi
ec6af56fbd remove statusbar when inAppBrowser is open in andriod 2018-04-23 16:07:17 +00:00
Steve Gill
5581957078 CB-14030 Set VERSION to 3.0.1-dev (via coho) 2018-04-13 12:28:14 -07:00
Steve Gill
757022d85a CB-14030 Updated version and RELEASENOTES.md for release 3.0.0 (via coho) 2018-04-13 12:24:16 -07:00
Steve Gill
49a23e34ba Merge pull request #266 from jcesarmobile/cordovaDependencies
Update cordovaDependencies to allow plugin install
2018-04-13 11:59:32 -07:00
Julio César
4a5608a7a0 Update cordovaDependencies to allow plugin install 2018-04-13 11:26:53 +02:00
Steve Gill
220cb39f93 Set VERSION to 3.0.1-dev (via coho) 2018-04-12 17:16:16 -07:00
Steve Gill
200f7c1923 CB-14030 Updated version and RELEASENOTES.md for release 3.0.0 (via coho) 2018-04-12 17:06:22 -07:00
Steve Gill
974ca3309a Merge pull request #254 from NiklasMerz/loading-spinner
CB-13659 (iOS) Add hidespinner option
2018-04-12 12:04:06 -07:00
Joe Bowser
50db5c498c Merge pull request #263 from SailingSteve/CB-14013-InAppBrowser-AllowCustomSchemes
CB-14013: (android) Change the InAppBrowser to allow custom schemes for oAuth
2018-04-12 12:01:59 -07:00
Steve Gill
013a861493 Merge pull request #260 from bentleyo/navigation-buttons
Fix nav buttons on iOS and allow custom color
2018-04-12 11:40:20 -07:00
stevepodell
42df297724 In file AppBrowser.java: New code within shouldOverrideUrlLoading() to
check for whitelisting custom schemes via a new "AllowedSchemes"
preference configuration item.  Allows custom schemes like
"mycoolapp://" or "wevotetwitterscheme://"

In file inappbrowser.js: Added new "customscheme" channel.
2018-04-05 12:45:02 -07:00
stevepodell
27500c2990 In file AppBrowser.java: New code within shouldOverrideUrlLoading() to
check for whitelisting custom schemes via a new "AllowedSchemes"
preference configuration item.  Allows custom schemes like
"mycoolapp://" or "wevotetwitterscheme://"

In file inappbrowser.js: Added new "customscheme" channel.
2018-04-05 11:54:32 -07:00
stevepodell
4c4bee528e InAppBrowser.java: New method isURLWhileListed to check for whitelisting of
"AllowedSchemes" in a new preference configuration item.
There is a new check in shouldOverrideUrlLoading, to allow whitelisted
custom schemes like "mycoolapp://"

inappbrowser.js: Added "customscheme" channel.
2018-04-05 10:31:00 -07:00
stevepodell
019ec3963f InAppBrowser.java: New method isURLWhileListed to check for whitelisting of
"AllowedSchemes" in a new preference configuration item.
There is a new check in shouldOverrideUrlLoading, to allow whitelisted
custom schemes like "mycoolapp://"

inappbrowser.js: Added "customscheme" channel.
2018-04-05 10:14:54 -07:00
stevepodell
2d69afcd7c InAppBrowser.java: New method isURLWhileListed to check for whitelisting.
Newtest in shouldOverrideUrlLoading, to allow whitelisted custom schemes
like"mycoolapp://"

inappbrowser.js: Added "customscheme" channel.
2018-04-04 15:57:13 -07:00
stevepodell
a6c7b54998 InAppBrowser.java: New method isURLWhileListed to check for whitelisting.
Newtest in shouldOverrideUrlLoading, to allow whitelisted custom schemes
like"mycoolapp://"

inappbrowser.js: Added "customscheme" channel.
2018-04-04 08:42:00 -07:00
stevepodell
44d9bb0f6a InAppBrowser.java: New method isURLWhileListed to check for whitelisting.
Newtest in shouldOverrideUrlLoading, to allow whitelisted custom schemes
like"mycoolapp://"

inappbrowser.js: Added "customscheme" channel.
2018-04-04 08:22:23 -07:00
Bentley O'Kane-Chase
65a825a193 Add customisation of the navigation buttons for iOS 2018-03-21 21:50:25 +10:00
Landsbankinn
b06ad8ed97 CB-13696 fixing for PR 2018-03-13 11:48:15 +00:00
Landsbankinn
cbe3a428f4 CB-13969 cordova-inappbrowser:iOS&Android now includes a extra, optional parameter to swap position of navigationbuttons and close/done button 2018-03-13 11:39:22 +00:00
Landsbankinn
313e0ae6f9 Merge remote-tracking branch 'upstream/master' 2018-03-06 16:58:35 +00:00
Bentley O'Kane-Chase
a3fca87ee5 Fix navigation buttons on iOS 2018-02-22 15:09:09 +10:00
Suraj Pindoria
3f0528c380 CB-13826 Incremented plugin version. 2018-01-25 11:47:20 -08:00
Suraj Pindoria
7eb2e1ea03 CB-13826 Updated version and RELEASENOTES.md for release 2.0.2 2018-01-25 11:41:40 -08:00
Joe Bowser
98ee2e148c Merge pull request #258 from dpa99c/CB-13791
CB-13791: (android) Add Android support for a footer close button
2018-01-24 09:51:19 -08:00
Dave Alden
b73ba93884 CB-13791: Add Android support for a footer close button 2018-01-17 20:13:19 +00:00
Joe Bowser
c80c338e51 Merge pull request #246 from landsbankinn/CB-13409
Cb 13409 - Add more configurable options for toolbar in android and ios
2018-01-17 11:04:07 -08:00
jcesarmobile
8e3f2f2c53 Merge pull request #257 from jcesarmobile/CB-13746
CB-13746: Add build-tools-26.0.2 to travis
2018-01-09 23:33:54 +01:00
Julio César
8f66f075dd CB-13746: Add build-tools-26.0.2 to travis 2018-01-09 20:28:45 +01:00
Simon MacDonald
1876869a05 Merge pull request #256 from jcesarmobile/fix-release-notes
Fix release notes
2017-12-30 00:57:27 -05:00
Julio César
260542d13c Fix release notes 2017-12-28 20:38:45 +01:00
Simon MacDonald
b9e0a80837 Set VERSION to 2.0.2-dev (via coho) 2017-12-27 19:13:50 -05:00
Simon MacDonald
7c1ea3b5c2 CB-13714 Updated version and RELEASENOTES.md for release 2.0.1 (via coho) 2017-12-27 19:13:36 -05:00
jcesarmobile
3a2c4ef5c0 Merge pull request #255 from jcesarmobile/CB-13699
CB-13699: Fix to allow 2.0.0 version install
2017-12-26 19:13:35 +01:00
Julio César
5f072a752d CB-13699: Fix to allow 2.0.0 version install 2017-12-26 18:22:29 +01:00
Steve Gill
e428556e25 Set VERSION to 2.0.1-dev (via coho) 2017-12-15 17:26:44 -08:00
Steve Gill
d85991accb CB-13681 Updated version and RELEASENOTES.md for release 2.0.0 (via coho) 2017-12-15 17:25:13 -08:00
Steve Gill
309cdef070 Merge pull request #253 from surajpindoria/removePlatforms
CB-13662: remove deprecated platforms
2017-12-13 17:32:28 -08:00
Niklas Merz
695e1b0f02 CB-13659 (iOS) Add hidespinner option
Signed-off-by: Niklas Merz <NiklasMerz@gmx.net>
2017-12-13 22:22:57 +01:00
Suraj Pindoria
2c547a1a1e CB-13662: remove deprecated platforms 2017-12-12 14:01:38 -08:00
Landsbankinn
84a4644cd1 Merge branch 'master' of https://github.com/apache/cordova-plugin-inappbrowser into CB-13409 2017-11-23 11:04:07 +00:00
Steve Gill
0f2f14a563 Set VERSION to 1.7.3-dev (via coho) 2017-11-06 14:38:39 -08:00
Steve Gill
b9c577044c CB-13542 Updated version and RELEASENOTES.md for release 1.7.2 (via coho) 2017-11-06 14:37:45 -08:00
Alexander Sorokin
cc2299e1c3 CB-13473: (CI) Removed browser builds from AppVeyor 2017-10-20 10:22:46 +03:00
Alexander Sorokin
7fb19f6bdc CB-13472: (CI) Fixed Travis Android builds again 2017-10-20 08:59:05 +03:00
Landsbankinn
d46f5d45d5 CB-13409: restore gitignore to default 2017-10-09 16:18:09 +00:00
Landsbankinn
ff230d429a CB-13409: restore gitignore to default 2017-10-09 16:18:09 +00:00
Landsbankinn
ec2f12c872 CB-13409: restore gitignore to default 2017-10-09 16:18:09 +00:00
Landsbankinn
6c2a8f4576 CB-13409: restore gitignore to default 2017-10-09 16:18:08 +00:00
Landsbankinn
55b02285f9 CB-13409: ignore idea folder 2017-10-09 16:17:59 +00:00
Landsbankinn
4af420c592 CB-13409: change hidetoolbarnavigationbuttons to hidenavigationbuttons in iso 2017-10-09 16:17:52 +00:00
Landsbankinn
e691212c96 CB-13409: Android works well now, all changes are now documented 2017-10-09 16:17:44 +00:00
Landsbankinn
8711ee3f21 CB-13409: Lets user adjust color of toolbar, hide navigation buttons and set custom text on close button 2017-10-09 16:17:14 +00:00
Landsbankinn
05e37a1ff1 ignore idea folder 2017-10-09 13:50:12 +00:00
Landsbankinn
0c6189e1a2 change hidetoolbarnavigationbuttons to hidenavigationbuttons in iso 2017-10-06 15:35:28 +00:00
Landsbankinn
d940b596b6 Android works well now, all changes are now documented 2017-10-06 14:45:12 +00:00
Landsbankinn
f3d7f72c9e Lets user adjust color of toolbar, hide navigation buttons and set custom text on close button 2017-10-06 14:45:00 +00:00
Joe Bowser
71201b10a6 Updating travis to fix CI issues 2017-09-27 10:03:13 -07:00
Joe Bowser
50ac05ca41 Close #165 2017-09-27 09:59:08 -07:00
Kei Oikawa
dcc00fc3bd CB-13347: Enable thirdparty cookies on >=Android 5.0 device 2017-09-27 09:57:43 -07:00
Joe Bowser
e9878ddecd Close #240 2017-09-27 09:49:06 -07:00
Jez McKean
aee699a0e5 minor grammar fix
This closes #241
2017-09-27 09:46:47 -07:00
Joe Bowser
d78cfdc4d4 Close #220 2017-09-21 09:39:38 -07:00
Joe Bowser
bf6945feb0 Close #201 2017-09-21 09:36:57 -07:00
Joe Bowser
ad4a0a3120 Close #221 2017-09-21 09:35:55 -07:00
Joe Bowser
3882924c4a Close #172 2017-09-21 09:32:57 -07:00
Joe Bowser
6eb9bbbf75 Close #156 2017-09-21 09:26:57 -07:00
Joe Bowser
7ac56842aa Close #116 2017-09-21 09:19:22 -07:00
Joe Bowser
dbf3316df3 Close #77 2017-09-21 09:10:08 -07:00
Joe Bowser
171e7dfea7 Close #73 2017-09-21 09:09:01 -07:00
Joe Bowser
6ea100a9fe Close #62 2017-09-21 09:05:30 -07:00
Alexander Sorokin
bfe8763918 CB-13299 (CI) Fix Android builds 2017-09-19 09:06:34 +03:00
Audrey So
902427525f CB-12895 : added eslint and removed jshint 2017-08-29 15:13:21 -07:00
Jan Piotrowski
7611645469 CB-12975 (docs) Resort and reword cordova.InAppBrowser.open options lists
for better developer experience
2017-08-01 11:55:59 -07:00
Alexander Sorokin
72ac4d7eca CB-13028 (CI) Browser builds on Travis and AppVeyor, Fixes tests on browser and browser implementation 2017-07-27 15:55:11 +03:00
Julio César
32d867f8e4 CB-12586 (iOS) fix method hide doesn't work
This closes #229
2017-07-23 19:02:19 +02:00
Julio César
6e058624d6 CB-13035 fix Create issue Link
This closes #228
2017-07-23 18:59:52 +02:00
Alexander Sorokin
ed139eeb34 CB-13000: (CI) Speed up android builds 2017-07-10 10:34:27 +03:00
Alexander Sorokin
aa82a5d6c8 CB-12991: (CI) Updated CI badges 2017-07-07 10:54:24 +03:00
Alexander Sorokin
15685d7a21 CB-12935: (windows) Enable paramedic builds on AppVeyor 2017-06-30 09:31:52 +03:00
Alexander Sorokin
4f144d9e82 CB-12935: (ios, android) Enable paramedic builds on Travis CI 2017-06-26 13:31:31 +03:00
Nikita Matrosov
b6ed0bbaca Add 'hide' method in typing definitions 2017-06-07 16:13:16 +03:00
filmaj
711c605212 CB-12847: added bugs entry to package.json. 2017-05-25 12:45:34 +02:00
filmaj
c630159c22 Set VERSION to 1.7.2-dev (via coho) 2017-04-27 12:51:10 -07:00
filmaj
ff6a765fac CB-12736 Updated version and RELEASENOTES.md for release 1.7.1 (via coho) 2017-04-27 12:51:08 -07:00
Alexander Sorokin
531a508c0d CB-12622: Added Android 6.0 build badges to README 2017-04-26 16:07:45 +03:00
filmaj
bfb33988be CB-12266: (browser platform) loadstop event.url is now a string instead of an object, aligning it with the other platforms. 2017-04-25 16:19:48 -07:00
Steve Gill
b923e88b23 CB-12685: added package.json to tests folder 2017-04-21 19:21:11 -07:00
daserge
c9ff78abfd CB-11248 InAppBrowser no focus on input text fields 2017-03-20 12:21:04 +03:00
Steve Gill
0f5de8524f CB-12519 updated incorrect version in RELEASENOTES.md 2017-03-02 16:42:02 -08:00
Steve Gill
0ddc31d3f4 Set VERSION to 1.7.1-dev (via coho) 2017-03-02 14:46:15 -08:00
Steve Gill
a74510ba00 CB-12519 Updated version and RELEASENOTES.md for release 1.7.0 2017-02-28 17:41:27 -08:00
74 changed files with 2723 additions and 10155 deletions

33
.appveyor.yml Normal file
View File

@@ -0,0 +1,33 @@
# appveyor file
# http://www.appveyor.com/docs/appveyor-yml
max_jobs: 1
shallow_clone: true
init:
- git config --global core.autocrlf true
image:
- Visual Studio 2017
environment:
matrix:
- nodejs_version: "10"
- nodejs_version: "12"
platform:
- x86
- x64
install:
- ps: Install-Product node $env:nodejs_version
- node --version
- npm install -g cordova-paramedic@https://github.com/apache/cordova-paramedic.git
- npm install -g cordova
- npm install
build: off
test_script:
- cordova-paramedic --config pr\windows-10-store --plugin . --justBuild

22
.asf.yaml Normal file
View File

@@ -0,0 +1,22 @@
# 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.
notifications:
commits: commits@cordova.apache.org
issues: issues@cordova.apache.org
pullrequests_status: issues@cordova.apache.org
pullrequests_comment: issues@cordova.apache.org

10
.eslintrc.yml Normal file
View File

@@ -0,0 +1,10 @@
root: true
extends: semistandard
rules:
indent:
- error
- 4
camelcase: off
padded-blocks: off
operator-linebreak: off
no-throw-literal: off

26
.gitattributes vendored Normal file
View File

@@ -0,0 +1,26 @@
* text eol=lf
#
## These files are binary and should be left untouched
#
# (binary is a macro for -text -diff)
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.mov binary
*.mp4 binary
*.mp3 binary
*.flv binary
*.fla binary
*.swf binary
*.gz binary
*.zip binary
*.7z binary
*.ttf binary
*.eot binary
*.woff binary
*.pyc binary
*.pdf binary

42
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,42 @@
<!--
Please have a look at the issue templates you get when you click "New issue" in the GitHub UI.
We very much prefer issues created by using one of these templates.
-->
### Issue Type
<!-- Please check the boxes by putting an x in the [ ] like so: [x] -->
- [ ] Bug Report
- [ ] Feature Request
- [ ] Support Question
## Description
## Information
<!-- Include all relevant information that might help understand and reproduce the problem -->
### Command or Code
<!-- What command or code is needed to reproduce the problem? -->
### Environment, Platform, Device
<!-- In what environment, on what platform or on which device are you experiencing the issue? -->
### Version information
<!--
What are relevant versions you are using?
For example:
Cordova: Cordova CLI, Cordova Platforms, Cordova Plugins
Other Frameworks: Ionic Framework and CLI version
Operating System, Android Studio, Xcode etc.
-->
## Checklist
<!-- Please check the boxes by putting an `x` in the `[ ]` like so: `[x]` -->
- [ ] I searched for already existing GitHub issues about this
- [ ] I updated all Cordova tooling to their most recent version
- [ ] I included all the necessary information above

50
.github/ISSUE_TEMPLATE/BUG_REPORT.md vendored Normal file
View File

@@ -0,0 +1,50 @@
---
name: 🐛 Bug Report
about: If something isn't working as expected.
---
# Bug Report
## Problem
### What is expected to happen?
### What does actually happen?
## Information
<!-- Include all relevant information that might help understand and reproduce the problem -->
### Command or Code
<!-- What command or code is needed to reproduce the problem? -->
### Environment, Platform, Device
<!-- In what environment, on what platform or on which device are you experiencing the issue? -->
### Version information
<!--
What are relevant versions you are using?
For example:
Cordova: Cordova CLI, Cordova Platforms, Cordova Plugins
Other Frameworks: Ionic Framework and CLI version
Operating System, Android Studio, Xcode etc.
-->
## Checklist
<!-- Please check the boxes by putting an x in the [ ] like so: [x] -->
- [ ] I searched for existing GitHub issues
- [ ] I updated all Cordova tooling to most recent version
- [ ] I included all the necessary information above

View File

@@ -0,0 +1,29 @@
---
name: 🚀 Feature Request
about: A suggestion for a new functionality
---
# Feature Request
## Motivation Behind Feature
<!-- Why should this feature be implemented? What problem does it solve? -->
## Feature Description
<!--
Describe your feature request in detail
Please provide any code examples or screenshots of what this feature would look like
Are there any drawbacks? Will this break anything for existing users?
-->
## Alternatives or Workarounds
<!--
Describe alternatives or workarounds you are currently using
Are there ways to do this with existing functionality?
-->

View File

@@ -0,0 +1,27 @@
---
name: 💬 Support Question
about: If you have a question, please check out our Slack or StackOverflow!
---
<!------------^ Click "Preview" for a nicer view! -->
Apache Cordova uses GitHub Issues as a feature request and bug tracker _only_.
For usage and support questions, please check out the resources below. Thanks!
---
You can get answers to your usage and support questions about **Apache Cordova** on:
* Slack Community Chat: https://cordova.slack.com (you can sign-up at http://slack.cordova.io/)
* StackOverflow: https://stackoverflow.com/questions/tagged/cordova using the tag `cordova`
---
If you are using a tool that uses Cordova internally, like e.g. Ionic, check their support channels:
* **Ionic Framework**
* [Ionic Community Forum](https://forum.ionicframework.com/)
* [Ionic Worldwide Slack](https://ionicworldwide.herokuapp.com/)
* **PhoneGap**
* [PhoneGap Developer Community](https://forums.adobe.com/community/phonegap)

View File

@@ -1,6 +1,5 @@
<!--
Please make sure the checklist boxes are all checked before submitting the PR. The checklist
is intended as a quick reference, for complete details please see our Contributor Guidelines:
Please make sure the checklist boxes are all checked before submitting the PR. The checklist is intended as a quick reference, for complete details please see our Contributor Guidelines:
http://cordova.apache.org/contribute/contribute_guidelines.html
@@ -10,13 +9,27 @@ Thanks!
### Platforms affected
### What does this PR do?
### Motivation and Context
<!-- Why is this change required? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here. -->
### What testing has been done on this change?
### Description
<!-- Describe your changes in detail -->
### Testing
<!-- Please describe in detail how you tested your changes. -->
### Checklist
- [ ] [Reported an issue](http://cordova.apache.org/contribute/issues.html) in the JIRA database
- [ ] Commit message follows the format: "CB-3232: (android) Fix bug with resolving file paths", where CB-xxxx is the JIRA ID & "android" is the platform affected.
- [ ] Added automated test coverage as appropriate for this change.
- [ ] I've run the tests to see all new and existing tests pass
- [ ] I added automated test coverage as appropriate for this change
- [ ] Commit is prefixed with `(platform)` if this change only applies to one platform (e.g. `(android)`)
- [ ] If this Pull Request resolves an issue, I linked to the issue in the text above (and used the correct [keyword to close issues using keywords](https://help.github.com/articles/closing-issues-using-keywords/))
- [ ] I've updated the documentation if necessary

2
.gitignore vendored
View File

@@ -11,6 +11,7 @@ Thumbs.db
*.log
*.swp
*.user
*.idea
node_modules
@@ -21,4 +22,3 @@ node_modules

View File

@@ -1,16 +0,0 @@
{
"browser": true
, "devel": true
, "bitwise": true
, "undef": true
, "trailing": true
, "quotmark": false
, "indent": 4
, "unused": "vars"
, "latedef": "nofunc"
, "globals": {
"module": false,
"exports": false,
"require": false
}
}

3
.npmignore Normal file
View File

@@ -0,0 +1,3 @@
.*
appveyor.yml
tests

View File

@@ -1,4 +1,118 @@
language: node_js
# This Travis configuration file is built after a Cordova Paramedic
# specific template with minimal modifications and adaptations:
# https://github.com/apache/cordova-paramedic/blob/master/.travis.yml
sudo: false
node_js:
- "4.2"
addons:
jwt:
# SAUCE_ACCESS_KEY
secure: TZ88IEvAw1bsWPWxvDzXdpi2NK0i3PN4hG15+vDpIt6wXGVPknjxuXWJeLj7TqBpAIvP7XDfS8ZvHVPLe7fe8oOchZPLuiDw9VVIk6cnHjE6wpoavdGc/1mDJ3Bi4PDcHwRUr5ng5spYQqqlTwcECkH/q7iPgudiFM6rlOlGRyA=
env:
global:
- SAUCE_USERNAME=snay
- TRAVIS_NODE_VERSION=12
- ANDROID_API_LEVEL=28
- ANDROID_BUILD_TOOLS_VERSION=28.0.3
language: node_js
node_js: 12
# yaml anchor/alias: https://medium.com/@tommyvn/travis-yml-dry-with-anchors-8b6a3ac1b027
_ios: &_ios
os: osx
osx_image: xcode10.3
_android: &_android
language: android
os: linux
jdk: oraclejdk8
android:
components:
- tools
- build-tools-$ANDROID_BUILD_TOOLS_VERSION
- android-$ANDROID_API_LEVEL
licenses:
- "android-sdk-preview-license-.+"
- "android-sdk-license-.+"
- "google-gdk-license-.+"
matrix:
include:
# local tests, without saucelabs
- env: PLATFORM=local/browser
<<: *_ios
- env: PLATFORM=local/ios-10.0
<<: *_ios
# many tests with saucelabs
- env: PLATFORM=browser-chrome
- env: PLATFORM=browser-firefox
- env: PLATFORM=browser-safari
- env: PLATFORM=browser-edge
- env: PLATFORM=ios-11.3
<<: *_ios
- env: PLATFORM=ios-12.0
<<: *_ios
- env: PLATFORM=android-5.1
<<: *_android
- env: PLATFORM=android-6.0
<<: *_android
- env: PLATFORM=android-7.0
<<: *_android
- env: PLATFORM=android-7.1
<<: *_android
- env: PLATFORM=android-8.0
<<: *_android
- env: PLATFORM=android-8.1
<<: *_android
- env: PLATFORM=android-9.0
<<: *_android
before_install:
# manually install Node for `language: android`
- if [[ "$PLATFORM" =~ android ]]; then nvm install $TRAVIS_NODE_VERSION; fi
- node --version
- if [[ "$PLATFORM" =~ android ]]; then gradle --version; fi
- if [[ "$PLATFORM" =~ ios ]]; then npm install -g ios-deploy; fi
- npm install -g cordova
# install paramedic if not running on paramedic repo
- if ! [[ "$TRAVIS_REPO_SLUG" =~ cordova-paramedic ]]; then npm install -g github:apache/cordova-paramedic; fi
install:
- npm install
before_script:
- |
if [[ "$TRAVIS_REPO_SLUG" =~ cordova-paramedic ]]; then
# when used in the cordova-paramedic repo
TEST_COMMAND="npm run eslint"
PARAMEDIC_PLUGIN_TO_TEST="./spec/testable-plugin/"
PARAMEDIC_COMMAND="node main.js"
else
# when used in any other (plugin) repo
TEST_COMMAND="npm test"
PARAMEDIC_PLUGIN_TO_TEST=$(pwd)
PARAMEDIC_COMMAND="cordova-paramedic"
fi
- PARAMEDIC_BUILDNAME=travis-$TRAVIS_REPO_SLUG-$TRAVIS_JOB_NUMBER
- |
echo "Variables now are set to:"
echo "TEST_COMMAND=$TEST_COMMAND"
echo "ADDITIONAL_TESTS=$ADDITIONAL_TESTS"
echo "PARAMEDIC_COMMAND=$PARAMEDIC_COMMAND"
echo "PLATFORM=$PLATFORM"
echo "PARAMEDIC_PLUGIN_TO_TEST=$PARAMEDIC_PLUGIN_TO_TEST"
echo "PARAMEDIC_BUILDNAME=$PARAMEDIC_BUILDNAME"
script:
- $TEST_COMMAND
- |
if [[ "$ADDITIONAL_TESTS_DIR" != "" ]]; then
cd $ADDITIONAL_TESTS_DIR && npm install && npm test;
else
$PARAMEDIC_COMMAND --config ./pr/$PLATFORM --plugin $PARAMEDIC_PLUGIN_TO_TEST --buildName $PARAMEDIC_BUILDNAME;
fi

View File

@@ -25,40 +25,13 @@ Anyone can contribute to Cordova. And we need your contributions.
There are multiple ways to contribute: report bugs, improve the docs, and
contribute code.
For instructions on this, start with the
[contribution overview](http://cordova.apache.org/contribute/).
The details are explained there, but the important items are:
- Sign and submit an Apache ICLA (Contributor License Agreement).
- Have a Jira issue open that corresponds to your contribution.
- Check for Github issues that corresponds to your contribution and link or create them if necessary.
- Run the tests so your patch doesn't break existing functionality.
We look forward to your contributions!
The notes on [Commit Workflow](https://github.com/apache/cordova-coho/blob/master/docs/committer-workflow.md#commit-workflow) can be helpful even if you are not a committer.
## Running plugin tests
* clone and install [cordova-plugin-test-framework](https://github.com/apache/cordova-plugin-test-framework)
```
git clone git@github.com:apache/cordova-plugin-test-framework.git
```
* edit ```cordova-plugin-test-framework/www/assets/index.html``` and add the following line
```
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com http://cordova.apache.org http://google.co.uk https://google.co.uk 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
```
* create test project
```
cordova create plugintest
cd plugintest
cordova platform add android
cordova plugin add ../cordova-plugin-inappbrowser
cordova plugin add ../cordova-plugin-inappbrowser/tests
cordova plugin add ../cordova-plugin-test-framework
```
* edit ```config.xml``` and replace ```<content src="index.html" />``` with ```<content src="cdvtests/index.html" />```
* run application
```
cordova run
```

212
README.md
View File

@@ -21,9 +21,9 @@ description: Open an in-app browser window.
# under the License.
-->
|Android 4.4|Android 5.1|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI|
|:-:|:-:|:-:|:-:|:-:|:-:|
|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-inappbrowser)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-inappbrowser/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-inappbrowser)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-inappbrowser/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-inappbrowser)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-inappbrowser/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-inappbrowser)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-inappbrowser/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-inappbrowser)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-inappbrowser/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)|
|AppVeyor|Travis CI|
|:-:|:-:|
|[![Build status](https://ci.appveyor.com/api/projects/status/github/apache/cordova-plugin-inappbrowser?branch=master)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-inappbrowser)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)|
# cordova-plugin-inappbrowser
@@ -35,12 +35,18 @@ This plugin provides a web browser view that displays when calling `cordova.InAp
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
### `window.open`
The `cordova.InAppBrowser.open()` function is defined to be a drop-in replacement
for the `window.open()` function. Existing `window.open()` calls can use the
InAppBrowser window, by replacing window.open:
window.open = cordova.InAppBrowser.open;
If you change the browsers `window.open` function this way, it can have unintended side
effects (especially if this plugin is included only as a dependency of another
plugin).
The InAppBrowser window behaves like a standard web browser,
and can't access Cordova APIs. For this reason, the InAppBrowser is recommended
if you need to load third-party (untrusted) content, instead of loading that
@@ -50,26 +56,6 @@ whitelist, nor is opening links in the system browser.
The InAppBrowser provides by default its own GUI controls for the user (back,
forward, done).
For backwards compatibility, this plugin also hooks `window.open`.
However, the plugin-installed hook of `window.open` can have unintended side
effects (especially if this plugin is included only as a dependency of another
plugin). The hook of `window.open` will be removed in a future major release.
Until the hook is removed from the plugin, apps can manually restore the default
behaviour:
delete window.open // Reverts the call back to it's prototype's default
Although `window.open` is in the global scope, InAppBrowser is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
Report issues with this plugin on the [Apache Cordova issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20%28Open%2C%20%22In%20Progress%22%2C%20Reopened%29%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20InAppBrowser%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC)
## <a id="reference">Reference</a>
## Installation
cordova plugin add cordova-plugin-inappbrowser
@@ -101,106 +87,87 @@ instance, or the system 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:
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:
- __location__: Set to `yes` or `no` to turn the `InAppBrowser`'s location bar on or off.
Android only:
Android supports these additional options:
- __hidden__: set to `yes` to create the browser and load the page, but not show it. The loadstop event fires when loading is complete. Omit or set to `no` (default) to have the browser open and load normally.
- __beforeload__: set to enable the `beforeload` event to modify which pages are actually loaded in the browser. Accepted values are `get` to intercept only GET requests, `post` to intercept on POST requests or `yes` to intercept both GET & POST requests. Note that POST requests are not currently supported and will be ignored (if you set `beforeload=post` it will raise an error).
- __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
- __zoom__: set to `yes` to show Android browser's zoom controls, set to `no` to hide them. Default value is `yes`.
- __closebuttoncaption__: set to a string to use as the close button's caption instead of a X. Note that you need to localize this value yourself.
- __closebuttoncolor__: set to a valid hex color string, for example: `#00ff00`, and it will change the
close button color from default, regardless of being a text or default X. Only has effect if user has location set to `yes`.
- __footer__: set to `yes` to show a close button in the footer similar to the iOS __Done__ button.
The close button will appear the same as for the header hence use __closebuttoncaption__ and __closebuttoncolor__ to set its properties.
- __footercolor__: set to a valid hex color string, for example `#00ff00` or `#CC00ff00` (`#aarrggbb`) , and it will change the footer color from default.
Only has effect if user has __footer__ set to `yes`.
- __hardwareback__: set to `yes` to use the hardware back button to navigate backwards through the `InAppBrowser`'s history. If there is no previous page, the `InAppBrowser` will close. The default value is `yes`, so you must set it to `no` if you want the back button to simply close the InAppBrowser.
- __hidenavigationbuttons__: set to `yes` to hide the navigation buttons on the location toolbar, only has effect if user has location set to `yes`. The default value is `no`.
- __hideurlbar__: set to `yes` to hide the url bar on the location toolbar, only has effect if user has location set to `yes`. The default value is `no`.
- __navigationbuttoncolor__: set to a valid hex color string, for example: `#00ff00`, and it will change the color of both navigation buttons from default. Only has effect if user has location set to `yes` and not hidenavigationbuttons set to `yes`.
- __toolbarcolor__: set to a valid hex color string, for example: `#00ff00`, and it will change the color the toolbar from default. Only has effect if user has location set to `yes`.
- __lefttoright__: Set to `yes` to swap positions of the navigation buttons and the close button. Specifically, navigation buttons go to the right and close button to the left. Default value is `no`.
- __zoom__: set to `yes` to show Android browser's zoom controls, set to `no` to hide them. Default value is `yes`.
- __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`).
- __fullscreen__: Sets whether the InappBrowser WebView is displayed fullscreen or not. In fullscreen mode, the status bar is hidden. Default value is `yes`.
iOS only:
iOS supports these additional options:
- __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 loadstop event fires when loading is complete. Omit or set to `no` (default) to have the browser open and load normally.
- __beforeload__: set to enable the `beforeload` event to modify which pages are actually loaded in the browser. Accepted values are `get` to intercept only GET requests, `post` to intercept on POST requests or `yes` to intercept both GET & POST requests. Note that POST requests are not currently supported and will be ignored (if you set `beforeload=post` it will raise an error).
- __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
- __clearsessioncache__: set to `yes` to have the session cookie cache cleared before the new window is opened. For WKWebView, requires iOS 11+ on target device.
- __cleardata__: set to `yes` to have the browser's entire local storage cleared (cookies, HTML5 local storage, IndexedDB, etc.) before the new window is opened
- __closebuttoncolor__: set as a valid hex color string, for example: `#00ff00`, to change from the default __Done__ button's color. Only applicable if toolbar is not disabled.
- __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 the bounce of the WKWebView's UIScrollView.
- __hidenavigationbuttons__: set to `yes` or `no` to turn the toolbar navigation buttons on or off (defaults to `no`). Only applicable if toolbar is not disabled.
- __navigationbuttoncolor__: set as a valid hex color string, for example: `#00ff00`, to change from the default color. Only applicable if navigation buttons are visible.
- __toolbar__: set to `yes` or `no` to turn the toolbar on or off for the InAppBrowser (defaults to `yes`)
- __toolbarcolor__: set as a valid hex color string, for example: `#00ff00`, to change from the default color of the toolbar. Only applicable if toolbar is not disabled.
- __toolbartranslucent__: set to `yes` or `no` to make the toolbar translucent(semi-transparent) (defaults to `yes`). Only applicable if toolbar is not disabled.
- __lefttoright__: Set to `yes` to swap positions of the navigation buttons and the close button. Specifically, close button goes to the right and navigation buttons to the left.
- __enableViewportScale__: Set to `yes` or `no` to prevent viewport scaling through a meta tag (defaults to `no`).
- __mediaPlaybackRequiresUserAction__: Set to `yes` 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`).
- __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`).
- __presentationstyle__: Set to `pagesheet`, `formsheet` or `fullscreen` to set the [presentation style](https://developer.apple.com/documentation/uikit/uimodalpresentationstyle) (defaults to `fullscreen`).
- __transitionstyle__: Set to `fliphorizontal`, `crossdissolve` or `coververtical` to set the [transition style](https://developer.apple.com/documentation/uikit/uimodaltransitionstyle) (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`).
Windows only:
Windows supports these additional options:
- __hidden__: set to `yes` to create the browser and load the page, but not show it. The loadstop event fires when loading is complete. Omit or set to `no` (default) to have the browser open and load normally.
- __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.
- __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.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- Browser
- iOS
- OSX
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
- Windows
### Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS Quirks
As plugin doesn't enforce any design there is a need to add some CSS rules if
opened with `target='_blank'`. The rules might look like these
``` css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
```
### OSX Quirks
At the moment the only supported target in OSX is `_system`.
`_blank` and `_self` targets are not yet implemented and are ignored silently. Pull requests and patches to get these to work are greatly appreciated.
### Windows Quirks
Windows 8.0, 8.1 and Windows Phone 8.1 don't support remote urls to be opened in the Cordova WebView so remote urls are always showed in the system's web browser if opened with `target='_self'`.
On Windows 10 if the URL is NOT in the white list and is opened with `target='_self'` it will be showed in the system's web browser instead of InAppBrowser popup.
Similar to Firefox OS IAB window visual behaviour can be overridden via `inAppBrowserWrap`/`inAppBrowserWrapFullscreen` CSS classes
### Browser Quirks
- Plugin is implemented via iframe,
@@ -235,6 +202,8 @@ The object returned from a call to `cordova.InAppBrowser.open` when the target i
- __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.
- __beforeload__: event fires when the `InAppBrowser` decides whether to load an URL or not (only with option `beforeload` set).
- __message__: event fires when the `InAppBrowser` receives a message posted from the page loaded inside the `InAppBrowser` Webview.
- __callback__: the function that executes when the event fires. The function is passed an `InAppBrowserEvent` object as a parameter.
@@ -248,7 +217,7 @@ function showHelp(url) {
var target = "_blank";
var options = "location=yes,hidden=yes";
var options = "location=yes,hidden=yes,beforeload=yes";
inAppBrowserRef = cordova.InAppBrowser.open(url, target, options);
@@ -258,6 +227,9 @@ function showHelp(url) {
inAppBrowserRef.addEventListener('loaderror', loadErrorCallBack);
inAppBrowserRef.addEventListener('beforeload', beforeloadCallBack);
inAppBrowserRef.addEventListener('message', messageCallBack);
}
function loadStartCallBack() {
@@ -270,7 +242,14 @@ function loadStopCallBack() {
if (inAppBrowserRef != undefined) {
inAppBrowserRef.insertCSS({ code: "body{font-size: 25px;" });
inAppBrowserRef.insertCSS({ code: "body{font-size: 25px;}" });
inAppBrowserRef.executeScript({ code: "\
var message = 'this is the message';\
var messageObj = {my_message: message};\
var stringifiedMessageObj = JSON.stringify(messageObj);\
webkit.messageHandlers.cordova_iab.postMessage(stringifiedMessageObj);"
});
$('#status-message').text("");
@@ -306,11 +285,29 @@ function executeScriptCallBack(params) {
}
function beforeloadCallBack(params, callback) {
if (params.url.startsWith("http://www.example.com/")) {
// Load this URL in the inAppBrowser.
callback(params.url);
} else {
// The callback is not invoked, so the page will not be loaded.
$('#status-message').text("This browser only opens pages on http://www.example.com/");
}
}
function messageCallBack(params){
$('#status-message').text("message received: "+params.data.my_message);
}
```
### InAppBrowserEvent Properties
- __type__: the eventname, either `loadstart`, `loadstop`, `loaderror`, or `exit`. _(String)_
- __type__: the eventname, either `loadstart`, `loadstop`, `loaderror`, `message` or `exit`. _(String)_
- __url__: the URL that was loaded. _(String)_
@@ -318,19 +315,24 @@ function executeScriptCallBack(params) {
- __message__: the error message, only in the case of `loaderror`. _(String)_
- __data__: the message contents , only in the case of `message`. A stringified JSON object. _(String)_
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
- iOS
- Windows
- OSX
### Browser Quirks
`loadstart` and `loaderror` events are not being fired.
`loadstart`, `loaderror`, `message` events are not fired.
### Windows Quirks
`message` event is not fired.
### Quick Example
@@ -351,18 +353,17 @@ function executeScriptCallBack(params) {
- __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.
- __message__: event fires when the `InAppBrowser` receives a message posted from the page loaded inside the `InAppBrowser` Webview.
- __callback__: the function to execute when the event fires.
The function is passed an `InAppBrowserEvent` object.
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
- iOS
- Windows
### Quick Example
@@ -381,13 +382,10 @@ The function is passed an `InAppBrowserEvent` object.
### Supported Platforms
- Amazon Fire OS
- Android
- Firefox OS
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
- iOS
- Windows
### Quick Example
@@ -404,11 +402,10 @@ The function is passed an `InAppBrowserEvent` object.
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Browser
- iOS
- Windows
### Quick Example
@@ -426,10 +423,9 @@ The function is passed an `InAppBrowserEvent` object.
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Windows
### Quick Example
@@ -458,11 +454,10 @@ The function is passed an `InAppBrowserEvent` object.
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Browser
- iOS
- Windows
### Quick Example
@@ -495,7 +490,6 @@ Due to [MSDN docs](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.cont
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows
@@ -613,7 +607,7 @@ function loadStopCallBack() {
if (inAppBrowserRef != undefined) {
inAppBrowserRef.insertCSS({ code: "body{font-size: 25px;" });
inAppBrowserRef.insertCSS({ code: "body{font-size: 25px;}" });
$('#status-message').text("");

View File

@@ -20,6 +20,130 @@
-->
# Release Notes
### 4.0.0 (Jun 09, 2020)
* [GH-715](https://github.com/apache/cordova-plugin-inappbrowser/pull/715) (ios): fix regression in 2706f34
* [GH-685](https://github.com/apache/cordova-plugin-inappbrowser/pull/685) chore: update install engines
* [GH-656](https://github.com/apache/cordova-plugin-inappbrowser/pull/656) (ios) Remove fake status bar with hardcoded height to fix issues in **iOS** devices with a notch
* [GH-693](https://github.com/apache/cordova-plugin-inappbrowser/pull/693) fix(ios): Allow loading local html files
* [GH-293](https://github.com/apache/cordova-plugin-inappbrowser/pull/293) **Android**: SSL errors handling in **Android**
* [GH-672](https://github.com/apache/cordova-plugin-inappbrowser/pull/672) fix(ios): prevent statusbar rotation after closing `InAppBrowser`
* chore(asf): update git notification settings
* [GH-669](https://github.com/apache/cordova-plugin-inappbrowser/pull/669) Allow App using `InAppBrowser` to be hosted in a cross-origin iframe
* [GH-600](https://github.com/apache/cordova-plugin-inappbrowser/pull/600) (all platforms): remove "window.open" overwrite
* [GH-670](https://github.com/apache/cordova-plugin-inappbrowser/pull/670) chore: bump version to 4.0.0-dev
* Update CONTRIBUTING.md
* [GH-662](https://github.com/apache/cordova-plugin-inappbrowser/pull/662) docs: replaces outdated transition and presentation style links
* [GH-666](https://github.com/apache/cordova-plugin-inappbrowser/pull/666) chore: remove deprecated orientation methods
* [GH-515](https://github.com/apache/cordova-plugin-inappbrowser/pull/515) Fix incorrect TypeScript typings
* [GH-654](https://github.com/apache/cordova-plugin-inappbrowser/pull/654) add check for openInSystem postNotification
* [GH-659](https://github.com/apache/cordova-plugin-inappbrowser/pull/659) ci: updates Node.js versions
* [GH-658](https://github.com/apache/cordova-plugin-inappbrowser/pull/658) chore(npm): improve ignore list
* [GH-442](https://github.com/apache/cordova-plugin-inappbrowser/pull/442) fix(android): Reset lefttoright if not set
* [GH-648](https://github.com/apache/cordova-plugin-inappbrowser/pull/648) (android) Correcting the documentation regarding lefttoright opt…
* [GH-634](https://github.com/apache/cordova-plugin-inappbrowser/pull/634) (android) Added option to turn on/off fullscreen mode in **Android**
* [GH-616](https://github.com/apache/cordova-plugin-inappbrowser/pull/616) (android) `InAppBrowser`: java.lang.IllegalArgumentException
* [GH-635](https://github.com/apache/cordova-plugin-inappbrowser/pull/635) breaking(ios): remove UIWebView
### 3.2.0 (Jan 04, 2020)
* [GH-503](https://github.com/apache/cordova-plugin-inappbrowser/pull/503) Defensive code to prevent NULL reference exceptions for async
* [GH-584](https://github.com/apache/cordova-plugin-inappbrowser/pull/584) Add compile-time decision for disabling UIWebView
* [GH-524](https://github.com/apache/cordova-plugin-inappbrowser/pull/524) Replace "beforeload" with BEFORELOAD
* [GH-568](https://github.com/apache/cordova-plugin-inappbrowser/pull/568) Update missing closed brace to the insert.CSS
* [GH-401](https://github.com/apache/cordova-plugin-inappbrowser/pull/401) Move createIframeBridge to injectDeferredObject
* [GH-534](https://github.com/apache/cordova-plugin-inappbrowser/pull/534) Fix `InAppBrowser` not opening on **iOS** 13
* ci(travis) Upgrade to node8
### 3.1.0 (Jun 27, 2019)
- chore: fix repo and issue urls and license in package.json and plugin.xml ([`8edfb9e`](https://github.com/apache/cordova-plugin-inappbrowser/commit/8edfb9e))
- chore: unknown changes because of linebreak change in binary files ([`e44ad91`](https://github.com/apache/cordova-plugin-inappbrowser/commit/e44ad91))
- build: add `.npmignore` to remove unneeded files from npm package ([`0ec4a11`](https://github.com/apache/cordova-plugin-inappbrowser/commit/0ec4a11))
- build: add `.gitattributes` to force LF (instead of possible CRLF on Windows) ([`2751255`](https://github.com/apache/cordova-plugin-inappbrowser/commit/2751255))
- ci(travis): Update Travis CI configuration for new paramedic ([#478](https://github.com/apache/cordova-plugin-inappbrowser/issues/478)) ([`c2bb6c1`](https://github.com/apache/cordova-plugin-inappbrowser/commit/c2bb6c1))
- docs: remove outdated translations ([`cc5ee00`](https://github.com/apache/cordova-plugin-inappbrowser/commit/cc5ee00))
- fix(android): Fix beforeload for Android &lt;= 7 ([#427](https://github.com/apache/cordova-plugin-inappbrowser/issues/427)) ([`94fec84`](https://github.com/apache/cordova-plugin-inappbrowser/commit/94fec84))
- ci(travis) Fix failing CI tests ([#460](https://github.com/apache/cordova-plugin-inappbrowser/issues/460)) ([`a162bd9`](https://github.com/apache/cordova-plugin-inappbrowser/commit/a162bd9))
- test: Fix test spec.5 to close inappbrowser after loadstop event ([#440](https://github.com/apache/cordova-plugin-inappbrowser/issues/440)) ([`5f1afbd`](https://github.com/apache/cordova-plugin-inappbrowser/commit/5f1afbd), [`af44235`](https://github.com/apache/cordova-plugin-inappbrowser/commit/af44235))
- fix(android): Prevent malformed callbackId from reaching app cordova view ([#436](https://github.com/apache/cordova-plugin-inappbrowser/issues/436)) ([`6861084`](https://github.com/apache/cordova-plugin-inappbrowser/commit/6861084), [`c95dbcb`](https://github.com/apache/cordova-plugin-inappbrowser/commit/c95dbcb))
- feat: [CB-13969](https://issues.apache.org/jira/browse/CB-13969): Allow close button and navigation buttons positions to be swapped ([#262](https://github.com/apache/cordova-plugin-inappbrowser/issues/262)) ([`d01bd25`](https://github.com/apache/cordova-plugin-inappbrowser/commit/d01bd25), [`f861655`](https://github.com/apache/cordova-plugin-inappbrowser/commit/f861655), [`9c7c2f3`](https://github.com/apache/cordova-plugin-inappbrowser/commit/9c7c2f3), [`3c0a42e`](https://github.com/apache/cordova-plugin-inappbrowser/commit/3c0a42e), [`5359f6c`](https://github.com/apache/cordova-plugin-inappbrowser/commit/5359f6c), [`df84dda`](https://github.com/apache/cordova-plugin-inappbrowser/commit/df84dda), [`2bcec40`](https://github.com/apache/cordova-plugin-inappbrowser/commit/2bcec40), [`fc0c560`](https://github.com/apache/cordova-plugin-inappbrowser/commit/fc0c560), [`5ead1e6`](https://github.com/apache/cordova-plugin-inappbrowser/commit/5ead1e6), [`c7931fa`](https://github.com/apache/cordova-plugin-inappbrowser/commit/c7931fa), [`e2adf1b`](https://github.com/apache/cordova-plugin-inappbrowser/commit/e2adf1b), [`4adf4c7`](https://github.com/apache/cordova-plugin-inappbrowser/commit/4adf4c7), [`cbe3a42`](https://github.com/apache/cordova-plugin-inappbrowser/commit/cbe3a42), [`74ccef1`](https://github.com/apache/cordova-plugin-inappbrowser/commit/74ccef1), [`ec6af56`](https://github.com/apache/cordova-plugin-inappbrowser/commit/ec6af56), [`b06ad8e`](https://github.com/apache/cordova-plugin-inappbrowser/commit/b06ad8e), [`313e0ae`](https://github.com/apache/cordova-plugin-inappbrowser/commit/313e0ae), [`05e37a1`](https://github.com/apache/cordova-plugin-inappbrowser/commit/05e37a1), [`0c6189e`](https://github.com/apache/cordova-plugin-inappbrowser/commit/0c6189e), [`d940b59`](https://github.com/apache/cordova-plugin-inappbrowser/commit/d940b59), [`f3d7f72`](https://github.com/apache/cordova-plugin-inappbrowser/commit/f3d7f72))
- docs: Add headline to window.open documentation ([#406](https://github.com/apache/cordova-plugin-inappbrowser/issues/406)) ([`92243cd`](https://github.com/apache/cordova-plugin-inappbrowser/commit/92243cd))
- fix(ios): Fix iframes in iOS/WKWebView which were broken by [#418](https://github.com/apache/cordova-plugin-inappbrowser/issues/418) ([#425](https://github.com/apache/cordova-plugin-inappbrowser/issues/425)) ([`388e3f6`](https://github.com/apache/cordova-plugin-inappbrowser/commit/388e3f6))
- chore(github): Add or update GitHub pull request and issue template ([`ae329bc`](https://github.com/apache/cordova-plugin-inappbrowser/commit/ae329bc))
- fix(ios): Handle non-default target attribute values (e.g. target=on links in WKWebView implementation on iOS ([#418](https://github.com/apache/cordova-plugin-inappbrowser/issues/418)) ([`9f4b729`](https://github.com/apache/cordova-plugin-inappbrowser/commit/9f4b729))
- fix(types): remove unused replace parameter ([#410](https://github.com/apache/cordova-plugin-inappbrowser/issues/410)) ([`6db2f2d`](https://github.com/apache/cordova-plugin-inappbrowser/commit/6db2f2d))
- documentation: Example documentation - Fix callBack function name ([#383](https://github.com/apache/cordova-plugin-inappbrowser/issues/383)) ([`a890e60`](https://github.com/apache/cordova-plugin-inappbrowser/commit/a890e60), [`2500b08`](https://github.com/apache/cordova-plugin-inappbrowser/commit/2500b08))
- fix: Fix beforeload to work with POST requests ([#367](https://github.com/apache/cordova-plugin-inappbrowser/issues/367)) ([`632a395`](https://github.com/apache/cordova-plugin-inappbrowser/commit/632a395))
- feat: (iOS & Android) Add postMessage API support ([#362](https://github.com/apache/cordova-plugin-inappbrowser/issues/362)) ([`c54d100`](https://github.com/apache/cordova-plugin-inappbrowser/commit/c54d100))
- fix(ios): Fixes loadAfterBeforeload on iOS. ([#350](https://github.com/apache/cordova-plugin-inappbrowser/issues/350)) ([`0fd43ae`](https://github.com/apache/cordova-plugin-inappbrowser/commit/0fd43ae))
- fix(ios): Fix crashes when using WKWebView implementation on iOS 9. ([#337](https://github.com/apache/cordova-plugin-inappbrowser/issues/337)) ([`3b82c16`](https://github.com/apache/cordova-plugin-inappbrowser/commit/3b82c16))
- fix(ios): Fix iOS CDVWKInAppBrowser evaluateJavascript method randomly gets blocked on ios 12 ([#341](https://github.com/apache/cordova-plugin-inappbrowser/issues/341)) ([`978b147`](https://github.com/apache/cordova-plugin-inappbrowser/commit/978b147))
- docs: remove unwanted information in README table ([#308](https://github.com/apache/cordova-plugin-inappbrowser/issues/308)) ([`3eadde6`](https://github.com/apache/cordova-plugin-inappbrowser/commit/3eadde6))
- fix(ios): This lets the default window layering do it's thing. ([#336](https://github.com/apache/cordova-plugin-inappbrowser/issues/336)) ([`c24bb46`](https://github.com/apache/cordova-plugin-inappbrowser/commit/c24bb46), [`27fe8ec`](https://github.com/apache/cordova-plugin-inappbrowser/commit/27fe8ec))
- feat(ios): [CB-7179](https://issues.apache.org/jira/browse/CB-7179) (iOS): Add optional WKWebView support for iOS ([#271](https://github.com/apache/cordova-plugin-inappbrowser/issues/271)) ([`10a0669`](https://github.com/apache/cordova-plugin-inappbrowser/commit/10a0669), [`3927b8f`](https://github.com/apache/cordova-plugin-inappbrowser/commit/3927b8f), [`8248215`](https://github.com/apache/cordova-plugin-inappbrowser/commit/8248215), [`61014dd`](https://github.com/apache/cordova-plugin-inappbrowser/commit/61014dd), [`c41f5b5`](https://github.com/apache/cordova-plugin-inappbrowser/commit/c41f5b5), [`19c6dfe`](https://github.com/apache/cordova-plugin-inappbrowser/commit/19c6dfe), [`7f5fa2a`](https://github.com/apache/cordova-plugin-inappbrowser/commit/7f5fa2a), [`5d2df21`](https://github.com/apache/cordova-plugin-inappbrowser/commit/5d2df21), [`86cc778`](https://github.com/apache/cordova-plugin-inappbrowser/commit/86cc778), [`cbfa195`](https://github.com/apache/cordova-plugin-inappbrowser/commit/cbfa195), [`52e3534`](https://github.com/apache/cordova-plugin-inappbrowser/commit/52e3534), [`8165232`](https://github.com/apache/cordova-plugin-inappbrowser/commit/8165232), [`e2210bd`](https://github.com/apache/cordova-plugin-inappbrowser/commit/e2210bd), [`dc7fa34`](https://github.com/apache/cordova-plugin-inappbrowser/commit/dc7fa34), [`b48e02f`](https://github.com/apache/cordova-plugin-inappbrowser/commit/b48e02f), [`27e6c67`](https://github.com/apache/cordova-plugin-inappbrowser/commit/27e6c67))
- docs: remove JIRA link ([`d9cafcd`](https://github.com/apache/cordova-plugin-inappbrowser/commit/d9cafcd))
- chore(types): [CB-12941](https://issues.apache.org/jira/browse/CB-12941): update typings ([#267](https://github.com/apache/cordova-plugin-inappbrowser/issues/267)) ([`a0c267f`](https://github.com/apache/cordova-plugin-inappbrowser/commit/a0c267f))
- feat: [CB-14188](https://issues.apache.org/jira/browse/CB-14188): add beforeload event, catching navigation before it happens ([#276](https://github.com/apache/cordova-plugin-inappbrowser/issues/276)) ([`228703a`](https://github.com/apache/cordova-plugin-inappbrowser/commit/228703a), [`eafaeda`](https://github.com/apache/cordova-plugin-inappbrowser/commit/eafaeda))
- ci(travis): reenable testing on all platforms ([`0ed0bf5`](https://github.com/apache/cordova-plugin-inappbrowser/commit/0ed0bf5))
- ci(travis): also accept terms for android sdk `android-27` ([`f8ad528`](https://github.com/apache/cordova-plugin-inappbrowser/commit/f8ad528))
- fix(android): [CB-10795](https://issues.apache.org/jira/browse/CB-10795): Exclude current app from external intent list ([#154](https://github.com/apache/cordova-plugin-inappbrowser/issues/154)) ([`a078337`](https://github.com/apache/cordova-plugin-inappbrowser/commit/a078337))
- fix(ios): [CB-14234](https://issues.apache.org/jira/browse/CB-14234): Don't call handleOpenURL for system URLs ([#278](https://github.com/apache/cordova-plugin-inappbrowser/issues/278)) ([`cf58b04`](https://github.com/apache/cordova-plugin-inappbrowser/commit/cf58b04))
- fix(ios): [CB-12875](https://issues.apache.org/jira/browse/CB-12875): (iOS) Pushes the inappbrowser window to a higher ui level than the existing apps window. ([#284](https://github.com/apache/cordova-plugin-inappbrowser/issues/284)) ([`dc5329d`](https://github.com/apache/cordova-plugin-inappbrowser/commit/dc5329d))
- ci: Quick CI fixes ([#277](https://github.com/apache/cordova-plugin-inappbrowser/issues/277)) ([`de86501`](https://github.com/apache/cordova-plugin-inappbrowser/commit/de86501), [`07d9a99`](https://github.com/apache/cordova-plugin-inappbrowser/commit/07d9a99), [`81f1437`](https://github.com/apache/cordova-plugin-inappbrowser/commit/81f1437), [`a464ea6`](https://github.com/apache/cordova-plugin-inappbrowser/commit/a464ea6), [`e75fe14`](https://github.com/apache/cordova-plugin-inappbrowser/commit/e75fe14), [`eb245ec`](https://github.com/apache/cordova-plugin-inappbrowser/commit/eb245ec))
- fix(ios): [CB-12922](https://issues.apache.org/jira/browse/CB-12922) (ios): fix In-app browser does not cede control ([#272](https://github.com/apache/cordova-plugin-inappbrowser/issues/272)) ([`dac06aa`](https://github.com/apache/cordova-plugin-inappbrowser/commit/dac06aa), [`9cc7f69`](https://github.com/apache/cordova-plugin-inappbrowser/commit/9cc7f69))
- fix(android): [CB-14061](https://issues.apache.org/jira/browse/CB-14061): (android) comply with RFC 3986 for custom URL scheme handling ([#269](https://github.com/apache/cordova-plugin-inappbrowser/issues/269)) ([`f57ede9`](https://github.com/apache/cordova-plugin-inappbrowser/commit/f57ede9), [`26cf6e4`](https://github.com/apache/cordova-plugin-inappbrowser/commit/26cf6e4))
- fix(android): [CB-14048](https://issues.apache.org/jira/browse/CB-14048): (android) allowedSchemes check empty string fix ([#268](https://github.com/apache/cordova-plugin-inappbrowser/issues/268)) ([`57eda78`](https://github.com/apache/cordova-plugin-inappbrowser/commit/57eda78), [`33aff11`](https://github.com/apache/cordova-plugin-inappbrowser/commit/33aff11))
### 3.0.0 (Apr 12, 2018)
* [CB-13659](https://issues.apache.org/jira/browse/CB-13659) **iOS** Add hidespinner option
* In file `AppBrowser.java`: New code within `shouldOverrideUrlLoading()` to check for whitelisting custom schemes via a new `AllowedSchemes` preference configuration item. Allows custom schemes like `mycoolapp://` or `wevotetwitterscheme://`
* `InAppBrowser.java`: New method `isURLWhileListed` to check for whitelisting of `AllowedSchemes` in a new preference configuration item. There is a new check in `shouldOverrideUrlLoading`, to allow whitelisted custom schemes like "mycoolapp://"
* Add customisation of the navigation buttons for **iOS**
* Fix navigation buttons on **iOS**
### 2.0.2 (Jan 24, 2018)
* [CB-13791](https://issues.apache.org/jira/browse/CB-13791) Add **Android** support for a footer close button
* [CB-13409](https://issues.apache.org/jira/browse/CB-13409) restore gitignore to default
* [CB-13409](https://issues.apache.org/jira/browse/CB-13409) restore gitignore to default
* [CB-13409](https://issues.apache.org/jira/browse/CB-13409) restore gitignore to default
* [CB-13409](https://issues.apache.org/jira/browse/CB-13409) restore gitignore to default
* [CB-13409](https://issues.apache.org/jira/browse/CB-13409) ignore idea folder
* [CB-13409](https://issues.apache.org/jira/browse/CB-13409) change hidetoolbarnavigationbuttons to hidenavigationbuttons in iso
* [CB-13409](https://issues.apache.org/jira/browse/CB-13409) **Android** works well now, all changes are now documented
* [CB-13409](https://issues.apache.org/jira/browse/CB-13409) Lets user adjust color of toolbar, hide navigation buttons and set custom text on close button
* [CB-13746](https://issues.apache.org/jira/browse/CB-13746) Add build-tools-26.0.2 to travis
### 2.0.1 (Dec 27, 2017)
* [CB-13699](https://issues.apache.org/jira/browse/CB-13699) Fix to allow 2.0.0 version install
### 2.0.0 (Dec 15, 2017)
* [CB-13662](https://issues.apache.org/jira/browse/CB-13662) remove deprecated platforms
### 1.7.2 (Nov 06, 2017)
* [CB-13473](https://issues.apache.org/jira/browse/CB-13473) (CI) Removed **Browser** builds from AppVeyor
* [CB-13472](https://issues.apache.org/jira/browse/CB-13472) (CI) Fixed Travis **Android** builds again
* [CB-13347](https://issues.apache.org/jira/browse/CB-13347) Enable thirdparty cookies on `>=Android 5.0` device
* [CB-12895](https://issues.apache.org/jira/browse/CB-12895) added `eslint` and removed `jshint`
* [CB-12975](https://issues.apache.org/jira/browse/CB-12975) (docs) Resort and reword `cordova.InAppBrowser.open` `options` lists
* [CB-12586](https://issues.apache.org/jira/browse/CB-12586) (iOS) fix method `hide` doesn't work
* [CB-12847](https://issues.apache.org/jira/browse/CB-12847) added `bugs` entry to `package.json`.
### 1.7.1 (Apr 27, 2017)
* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Added **Android 6.0** build badges to `README`
* [CB-12266](https://issues.apache.org/jira/browse/CB-12266) (browser platform) loadstop event.url is now a string instead of an object, aligning it with the other platforms.
* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder
* [CB-11248](https://issues.apache.org/jira/browse/CB-11248) `InAppBrowser` no focus on input text fields
### 1.7.0 (Feb 28, 2017)
* [CB-12366](https://issues.apache.org/jira/browse/CB-12366) **iOS:** Reduce `tmpWindow` level to prevent overlapping statusbar
* [CB-12364](https://issues.apache.org/jira/browse/CB-12364) **Windows:** `Inappbrowser` inject file manual tests are not working
* [CB-12353](https://issues.apache.org/jira/browse/CB-12353) Corrected merges usage in `plugin.xml`
* [CB-12369](https://issues.apache.org/jira/browse/CB-12369) Add plugin typings from `DefinitelyTyped`
* [CB-12363](https://issues.apache.org/jira/browse/CB-12363) Added build badges for **iOS 9.3** and **iOS 10.0**
* [CB-9148](https://issues.apache.org/jira/browse/CB-9148) **Android:** Add Support for `input[type=file]` File Chooser
* [CB-11136](https://issues.apache.org/jira/browse/CB-11136) (ios) Fix `InAppBrowser` when closing with `WKWebView`
* [CB-10799](https://issues.apache.org/jira/browse/CB-10799) **iOS:** fix toolbar is shown in incorrect position when in-call status bar
### 1.6.1 (Dec 14, 2016)
* [CB-12237](https://issues.apache.org/jira/browse/CB-12237) - Update version in package.json to correct 1.6.1-dev
* [CB-12236](https://issues.apache.org/jira/browse/CB-12236) - Fixed RELEASENOTES for cordova-plugin-inappbrowser

View File

@@ -1,388 +0,0 @@
<!--
# 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.
-->
# cordova-plugin-inappbrowser
[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)
Dieses Plugin bietet eine Web-Browser-Ansicht, die beim Aufruf von `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
Die `cordova.InAppBrowser.open()` Funktion ist definiert als Ersatz für die `window.open()` Funktion. InAppBrowser Fenster, können vorhandene `window.open()` Aufrufe durch window.open ersetzen:
window.open = cordova.InAppBrowser.open;
Das InAppBrowser-Fenster verhält sich wie einen standard-Webbrowser und Cordova APIs kann nicht zugegriffen werden kann. Aus diesem Grund empfiehlt sich die InAppBrowser Wenn Sie von Drittanbietern (nicht vertrauenswürdige) Inhalte, statt zu laden, die in den wichtigsten Cordova Webview laden müssen. Die InAppBrowser unterliegt nicht der weißen Liste, noch ist Links in der Systembrowser öffnen.
Die InAppBrowser bietet standardmäßig eine eigene GUI-Steuerelemente für den Benutzer (zurück, vor, erledigt).
Für rückwärts Kompatibilität, dieses Plugin auch `window.open` Haken. Jedoch kann der Plugin installiert Haken der `window.open` haben unbeabsichtigte Nebenwirkungen (vor allem, wenn dieses Plugin nur als eine Abhängigkeit von einem anderen Plugin enthalten ist). Der Haken der `window.open` wird in einer zukünftigen Version entfernt. Bis der Haken aus dem Plugin entfernt wird, können die Vorgabe von apps manuell wiederherstellen:
delete window.open // Reverts the call back to it's prototype's default
`window.open` im globalen Gültigkeitsbereich ist zwar InAppBrowser nicht verfügbar bis nach dem `deviceready`-Ereignis.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Installation
cordova plugin add cordova-plugin-inappbrowser
Wenn Sie alle Seite Lasten in Ihrer Anwendung durch die InAppBrowser gehen möchten, können Sie einfach `window.open` während der Initialisierung Haken. Zum Beispiel:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Öffnet eine URL in eine neue `InAppBrowser`-Instanz, die aktuelle Browserinstanz oder der Systembrowser.
var ref = cordova.InAppBrowser.open(url, target, options);
* **Ref**: Bezugnahme auf das `InAppBrowser` Fenster. *(InAppBrowser)*
* **URL**: die URL um den *(String)* zu laden. Rufen Sie `encodeURI()` auf, wenn die URL Unicode-Zeichen enthält.
* **target**: das Ziel in welchem die URL geladen werden soll. Standardmäßig entspricht dieser Wert `_self` . *(String)*
* `_self`: Öffnet sich in der Cordova WebView wenn der URL in der Whitelist ist, andernfalls es öffnet sich in der`InAppBrowser`.
* `_blank`: Öffnet den`InAppBrowser`.
* `_system`: Öffnet in den System-Web-Browser.
* **options**: Optionen für die `InAppBrowser` . Optional, säumige an: `location=yes` . *(String)*
Die `options` Zeichenfolge muss keine Leerstelle enthalten, und jede Funktion Name/Wert-Paare müssen durch ein Komma getrennt werden. Featurenamen Groß-/Kleinschreibung. Alle Plattformen unterstützen die anderen Werte:
* **location**: Legen Sie auf `yes` oder `no` , machen die `InAppBrowser` der Adressleiste ein- oder ausschalten.
Nur Android:
* **hidden**: Legen Sie auf `yes` um den Browser zu erstellen und laden Sie die Seite, aber nicht zeigen. Das Loadstop-Ereignis wird ausgelöst, wenn der Ladevorgang abgeschlossen ist. Weglassen oder auf `no` (Standard), den Browser öffnen und laden normalerweise zu haben.
* **clearcache**: Legen Sie auf `yes` , der Browser ist Cookiecache gelöscht, bevor das neue Fenster geöffnet wird
* **clearsessioncache**: Legen Sie auf `yes` zu der Session Cookie Cache gelöscht, bevor das neue Fenster geöffnet wird
* **zoom**: Legen Sie auf `yes` zu zeigen Android Browser-Zoom-Steuerelementen, die auf `no` festlegen, um sie zu verbergen. Standardwert ist `yes`.
* **hardwareback**: auf `yes` festlegen, um die Zurück-Taste verwenden, um die `InAppBrowser`Geschichte rückwärts navigieren. Wenn es keine vorherige Seite, wird der `InAppBrowser` geschlossen. Der Standardwert ist `yes`, so dass Sie es auf `no` festlegen müssen, wenn Sie die Schaltfläche "zurück", die InAppBrowser einfach zu schließen möchten.
iOS nur:
* **closebuttoncaption**: Legen Sie auf eine Zeichenfolge als Beschriftung der **fertig** -Schaltfläche verwenden. Beachten Sie, dass Sie diesen Wert selbst zu lokalisieren müssen.
* **disallowoverscroll**: Legen Sie auf `yes` oder `no` (Standard ist `no` ). Aktiviert/deaktiviert die UIWebViewBounce-Eigenschaft.
* **hidden**: Legen Sie auf `yes` um den Browser zu erstellen und laden Sie die Seite, aber nicht zeigen. Das Loadstop-Ereignis wird ausgelöst, wenn der Ladevorgang abgeschlossen ist. Weglassen oder auf `no` (Standard), den Browser öffnen und laden normalerweise zu haben.
* **clearcache**: Legen Sie auf `yes` , der Browser ist Cookiecache gelöscht, bevor das neue Fenster geöffnet wird
* **clearsessioncache**: Legen Sie auf `yes` zu der Session Cookie Cache gelöscht, bevor das neue Fenster geöffnet wird
* **toolbar**: Legen Sie auf `yes` oder `no` Aktivieren Sie die Symbolleiste ein- oder Ausschalten für InAppBrowser (Standard:`yes`)
* **enableViewportScale**: Legen Sie auf `yes` oder `no` , Viewport Skalierung durch ein Meta-Tag (standardmäßig zu verhindern`no`).
* **mediaPlaybackRequiresUserAction**: Legen Sie auf `yes` oder `no` , HTML5 audio oder video von automatisches Abspielen (standardmäßig zu verhindern`no`).
* **allowInlineMediaPlayback**: Legen Sie auf `yes` oder `no` Inline-HTML5-Media-Wiedergabe, Darstellung im Browser-Fenster, sondern in eine gerätespezifische Wiedergabe-Schnittstelle ermöglichen. Des HTML `video` Element muss auch die `webkit-playsinline` Attribut (Standard:`no`)
* **keyboardDisplayRequiresUserAction**: Legen Sie auf `yes` oder `no` um die Tastatur zu öffnen, wenn Formularelemente Fokus per JavaScript erhalten `focus()` Anruf (Standard:`yes`).
* **suppressesIncrementalRendering**: Legen Sie auf `yes` oder `no` zu warten, bis alle neuen anzeigen-Inhalte empfangen wird, bevor Sie wiedergegeben wird (standardmäßig`no`).
* **presentationstyle**: Legen Sie auf `pagesheet` , `formsheet` oder `fullscreen` [Präsentationsstil](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle) (standardmäßig fest`fullscreen`).
* **transitionstyle**: Legen Sie auf `fliphorizontal` , `crossdissolve` oder `coververtical` [Übergangsstil](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle) (standardmäßig fest`coververtical`).
* **toolbarposition**: Legen Sie auf `top` oder `bottom` (Standard ist `bottom` ). Bewirkt, dass die Symbolleiste am oberen oder unteren Rand des Fensters sein.
Nur Windows:
* **hidden**: Legen Sie auf `yes` um den Browser zu erstellen und laden Sie die Seite, aber nicht zeigen. Das Loadstop-Ereignis wird ausgelöst, wenn der Ladevorgang abgeschlossen ist. Weglassen oder auf `no` (Standard), den Browser öffnen und laden normalerweise zu haben.
* **fullscreen**: auf `yes` festlegen, um das WebBrowser-Steuerelement ohne Rahmen drumherum zu erstellen. Bitte beachten Sie, dass bei **location=no** wird auch angegeben, gibt es keine Kontrolle, die Benutzer zum IAB-Fenster schließen.
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 und 8.1
* Windows Phone 7 und 8
* Browser
### Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS Macken
Als Plugin jedes Design erzwingen nicht besteht die Notwendigkeit, einige CSS-Regeln hinzuzufügen, wenn bei `target='_blank'`. Die Regeln könnte wie diese aussehen.
```css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
```
### Windows-Eigenheiten
Ähnlich wie Firefox OS IAB Fenster visuelle Verhalten kann überschrieben werden, über `InAppBrowserWrap`/`InAppBrowserWrapFullscreen` -CSS-Klassen
### Browser-Eigenheiten
* Plugin wird per Iframe implementiert,
* Navigationsverlauf (Schaltflächen`zurück` und `Vorwärts` in LocationBar) ist nicht implementiert.
## InAppBrowser
Bei einem Aufruf von `cordova.InAppBrowser.open` zurückgegebene Objekt..
### Methoden
* addEventListener
* removeEventListener
* Schließen
* Karte
* executeScript
* insertCSS
## addEventListener
> Fügt einen Listener für eine Veranstaltung aus der`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **Ref**: Bezugnahme auf die `InAppBrowser` Fenster *(InAppBrowser)*
* **EventName**: das Ereignis zu warten *(String)*
* **Loadstart**: Ereignis wird ausgelöst, wenn die `InAppBrowser` beginnt, eine URL zu laden.
* **Loadstop**: Ereignis wird ausgelöst, wenn der `InAppBrowser` beendet ist, eine URL laden.
* **LoadError**: Ereignis wird ausgelöst, wenn der `InAppBrowser` ein Fehler auftritt, wenn Sie eine URL zu laden.
* **Ausfahrt**: Ereignis wird ausgelöst, wenn das `InAppBrowser` -Fenster wird geschlossen.
* **Rückruf**: die Funktion, die ausgeführt wird, wenn das Ereignis ausgelöst wird. Die Funktion übergeben wird ein `InAppBrowserEvent` -Objekt als Parameter.
### InAppBrowserEvent Eigenschaften
* **Typ**: Eventname, entweder `loadstart` , `loadstop` , `loaderror` , oder `exit` . *(String)*
* **URL**: die URL, die geladen wurde. *(String)*
* **Code**: der Fehler-Code, nur im Fall von `loaderror` . *(Anzahl)*
* **Nachricht**: die Fehlermeldung angezeigt, nur im Fall von `loaderror` . *(String)*
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* iOS
* Windows 8 und 8.1
* Windows Phone 7 und 8
* Browser
### Browser-Eigenheiten
`loadstart` und `loaderror` Ereignisse werden nicht ausgelöst wird.
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Entfernt einen Listener für eine Veranstaltung aus der`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **Ref**: Bezugnahme auf die `InAppBrowser` Fenster. *(InAppBrowser)*
* **EventName**: das Ereignis zu warten. *(String)*
* **Loadstart**: Ereignis wird ausgelöst, wenn die `InAppBrowser` beginnt, eine URL zu laden.
* **Loadstop**: Ereignis wird ausgelöst, wenn der `InAppBrowser` beendet ist, eine URL laden.
* **LoadError**: Ereignis wird ausgelöst, wenn die `InAppBrowser` trifft einen Fehler beim Laden einer URLs.
* **Ausfahrt**: Ereignis wird ausgelöst, wenn das `InAppBrowser` -Fenster wird geschlossen.
* **Rückruf**: die Funktion ausgeführt, wenn das Ereignis ausgelöst wird. Die Funktion übergeben wird ein `InAppBrowserEvent` Objekt.
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* iOS
* Windows 8 und 8.1
* Windows Phone 7 und 8
* Browser
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## Schließen
> Schließt die `InAppBrowser` Fenster.
ref.close();
* **Ref**: Bezugnahme auf die `InAppBrowser` Fenster *(InAppBrowser)*
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows 8 und 8.1
* Windows Phone 7 und 8
* Browser
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## Karte
> Zeigt ein InAppBrowser-Fenster, das geöffnet wurde, versteckt. Aufrufen, dies hat keine Auswirkungen, wenn die InAppBrowser schon sichtbar war.
ref.show();
* **Ref**: Verweis auf die (InAppBrowser) Fenster`InAppBrowser`)
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* iOS
* Windows 8 und 8.1
* Browser
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Fügt JavaScript-Code in das `InAppBrowser` Fenster
ref.executeScript(details, callback);
* **Ref**: Bezugnahme auf die `InAppBrowser` Fenster. *(InAppBrowser)*
* **InjectDetails**: Informationen über das Skript ausgeführt, angeben, entweder ein `file` oder `code` Schlüssel. *(Objekt)*
* **Datei**: URL des Skripts zu injizieren.
* **Code**: Text des Skripts zu injizieren.
* **Rückruf**: die Funktion, die ausgeführt wird, nachdem der JavaScript-Code injiziert wird.
* Wenn das eingefügte Skript vom Typ ist `code` , der Rückruf führt mit einen einzelnen Parameter, der der Rückgabewert des Skripts ist, umwickelt ein `Array` . Bei Multi-Line-Skripten ist der Rückgabewert von der letzten Anweisung oder den letzten Ausdruck ausgewertet.
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* iOS
* Windows 8 und 8.1
* Browser
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### Browser-Eigenheiten
* **code** -Schlüssel wird unterstützt.
### Windows-Eigenheiten
Aufgrund der [MSDN-Dokumentation](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx) das aufgerufene Skript kehren nur Zeichenfolgenwerte, andernfalls des Parameters, an **Rückruf** übergeben werden `[null]`.
## insertCSS
> Injiziert CSS in der `InAppBrowser` Fenster.
ref.insertCSS(details, callback);
* **Ref**: Bezugnahme auf die `InAppBrowser` Fenster *(InAppBrowser)*
* **InjectDetails**: Informationen über das Skript ausgeführt, angeben, entweder ein `file` oder `code` Schlüssel. *(Objekt)*
* **Datei**: URL des Stylesheets zu injizieren.
* **Code**: Text des Stylesheets zu injizieren.
* **Rückruf**: die Funktion, die ausgeführt wird, nachdem die CSS injiziert wird.
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* iOS
* Windows
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,357 +0,0 @@
<!---
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.
-->
# cordova-plugin-inappbrowser
Dieses Plugin bietet eine Web-Browser-Ansicht, die beim Aufruf von `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
Die `cordova.InAppBrowser.open()` Funktion ist definiert als Ersatz für die `window.open()` Funktion. InAppBrowser Fenster, können vorhandene `window.open()` Aufrufe durch window.open ersetzen:
window.open = cordova.InAppBrowser.open;
Das InAppBrowser-Fenster verhält sich wie einen standard-Webbrowser und Cordova APIs kann nicht zugegriffen werden kann. Aus diesem Grund empfiehlt sich die InAppBrowser Wenn Sie von Drittanbietern (nicht vertrauenswürdige) Inhalte, statt zu laden, die in den wichtigsten Cordova Webview laden müssen. Die InAppBrowser unterliegt nicht der weißen Liste, noch ist Links in der Systembrowser öffnen.
Die InAppBrowser bietet standardmäßig eine eigene GUI-Steuerelemente für den Benutzer (zurück, vor, erledigt).
Für rückwärts Kompatibilität, dieses Plugin auch `window.open` Haken. Jedoch kann der Plugin installiert Haken der `window.open` haben unbeabsichtigte Nebenwirkungen (vor allem, wenn dieses Plugin nur als eine Abhängigkeit von einem anderen Plugin enthalten ist). Der Haken der `window.open` wird in einer zukünftigen Version entfernt. Bis der Haken aus dem Plugin entfernt wird, können die Vorgabe von apps manuell wiederherstellen:
delete window.open // Reverts the call back to it's prototype's default
`window.open` im globalen Gültigkeitsbereich ist zwar InAppBrowser nicht verfügbar bis nach dem `deviceready`-Ereignis.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Installation
cordova plugin add cordova-plugin-inappbrowser
Wenn Sie alle Seite Lasten in Ihrer Anwendung durch die InAppBrowser gehen möchten, können Sie einfach `window.open` während der Initialisierung Haken. Zum Beispiel:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Öffnet eine URL in eine neue `InAppBrowser`-Instanz, die aktuelle Browserinstanz oder der Systembrowser.
var ref = cordova.InAppBrowser.open(url, target, options);
* **Ref**: Bezugnahme auf das `InAppBrowser` Fenster. *(InAppBrowser)*
* **URL**: die URL um den *(String)* zu laden. Rufen Sie `encodeURI()` auf, wenn die URL Unicode-Zeichen enthält.
* **target**: das Ziel in welchem die URL geladen werden soll. Standardmäßig entspricht dieser Wert `_self` . *(String)*
* `_self`: Öffnet sich in der Cordova WebView wenn der URL in der Whitelist ist, andernfalls es öffnet sich in der`InAppBrowser`.
* `_blank`: Öffnet den`InAppBrowser`.
* `_system`: Öffnet in den System-Web-Browser.
* **options**: Optionen für die `InAppBrowser` . Optional, säumige an: `location=yes` . *(String)*
Die `options` Zeichenfolge muss keine Leerstelle enthalten, und jede Funktion Name/Wert-Paare müssen durch ein Komma getrennt werden. Featurenamen Groß-/Kleinschreibung. Alle Plattformen unterstützen die anderen Werte:
* **location**: Legen Sie auf `yes` oder `no` , machen die `InAppBrowser` der Adressleiste ein- oder ausschalten.
Nur Android:
* **hidden**: Legen Sie auf `yes` um den Browser zu erstellen und laden Sie die Seite, aber nicht zeigen. Das Loadstop-Ereignis wird ausgelöst, wenn der Ladevorgang abgeschlossen ist. Weglassen oder auf `no` (Standard), den Browser öffnen und laden normalerweise zu haben.
* **clearcache**: Legen Sie auf `yes` , der Browser ist Cookiecache gelöscht, bevor das neue Fenster geöffnet wird
* **clearsessioncache**: Legen Sie auf `yes` zu der Session Cookie Cache gelöscht, bevor das neue Fenster geöffnet wird
iOS nur:
* **closebuttoncaption**: Legen Sie auf eine Zeichenfolge als Beschriftung der **fertig** -Schaltfläche verwenden. Beachten Sie, dass Sie diesen Wert selbst zu lokalisieren müssen.
* **disallowoverscroll**: Legen Sie auf `yes` oder `no` (Standard ist `no` ). Aktiviert/deaktiviert die UIWebViewBounce-Eigenschaft.
* **hidden**: Legen Sie auf `yes` um den Browser zu erstellen und laden Sie die Seite, aber nicht zeigen. Das Loadstop-Ereignis wird ausgelöst, wenn der Ladevorgang abgeschlossen ist. Weglassen oder auf `no` (Standard), den Browser öffnen und laden normalerweise zu haben.
* **clearcache**: Legen Sie auf `yes` , der Browser ist Cookiecache gelöscht, bevor das neue Fenster geöffnet wird
* **clearsessioncache**: Legen Sie auf `yes` zu der Session Cookie Cache gelöscht, bevor das neue Fenster geöffnet wird
* **toolbar**: Legen Sie auf `yes` oder `no` Aktivieren Sie die Symbolleiste ein- oder Ausschalten für InAppBrowser (Standard:`yes`)
* **enableViewportScale**: Legen Sie auf `yes` oder `no` , Viewport Skalierung durch ein Meta-Tag (standardmäßig zu verhindern`no`).
* **mediaPlaybackRequiresUserAction**: Legen Sie auf `yes` oder `no` , HTML5 audio oder video von automatisches Abspielen (standardmäßig zu verhindern`no`).
* **allowInlineMediaPlayback**: Legen Sie auf `yes` oder `no` Inline-HTML5-Media-Wiedergabe, Darstellung im Browser-Fenster, sondern in eine gerätespezifische Wiedergabe-Schnittstelle ermöglichen. Des HTML `video` Element muss auch die `webkit-playsinline` Attribut (Standard:`no`)
* **keyboardDisplayRequiresUserAction**: Legen Sie auf `yes` oder `no` um die Tastatur zu öffnen, wenn Formularelemente Fokus per JavaScript erhalten `focus()` Anruf (Standard:`yes`).
* **suppressesIncrementalRendering**: Legen Sie auf `yes` oder `no` zu warten, bis alle neuen anzeigen-Inhalte empfangen wird, bevor Sie wiedergegeben wird (standardmäßig`no`).
* **presentationstyle**: Legen Sie auf `pagesheet` , `formsheet` oder `fullscreen` [Präsentationsstil][1] (standardmäßig fest`fullscreen`).
* **transitionstyle**: Legen Sie auf `fliphorizontal` , `crossdissolve` oder `coververtical` [Übergangsstil][2] (standardmäßig fest`coververtical`).
* **toolbarposition**: Legen Sie auf `top` oder `bottom` (Standard ist `bottom` ). Bewirkt, dass die Symbolleiste am oberen oder unteren Rand des Fensters sein.
Nur Windows:
* **hidden**: Legen Sie auf `yes` um den Browser zu erstellen und laden Sie die Seite, aber nicht zeigen. Das Loadstop-Ereignis wird ausgelöst, wenn der Ladevorgang abgeschlossen ist. Weglassen oder auf `no` (Standard), den Browser öffnen und laden normalerweise zu haben.
[1]: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle
[2]: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 und 8.1
* Windows Phone 7 und 8
### Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS Macken
Als Plugin jedes Design erzwingen nicht besteht die Notwendigkeit, einige CSS-Regeln hinzuzufügen, wenn bei `target='_blank'`. Die Regeln könnte wie diese aussehen.
css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
## InAppBrowser
Bei einem Aufruf von `cordova.InAppBrowser.open` zurückgegebene Objekt..
### Methoden
* addEventListener
* removeEventListener
* Schließen
* Karte
* executeScript
* insertCSS
## addEventListener
> Fügt einen Listener für eine Veranstaltung aus der`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **Ref**: Bezugnahme auf die `InAppBrowser` Fenster *(InAppBrowser)*
* **EventName**: das Ereignis zu warten *(String)*
* **Loadstart**: Ereignis wird ausgelöst, wenn die `InAppBrowser` beginnt, eine URL zu laden.
* **Loadstop**: Ereignis wird ausgelöst, wenn der `InAppBrowser` beendet ist, eine URL laden.
* **LoadError**: Ereignis wird ausgelöst, wenn der `InAppBrowser` ein Fehler auftritt, wenn Sie eine URL zu laden.
* **Ausfahrt**: Ereignis wird ausgelöst, wenn das `InAppBrowser` -Fenster wird geschlossen.
* **Rückruf**: die Funktion, die ausgeführt wird, wenn das Ereignis ausgelöst wird. Die Funktion übergeben wird ein `InAppBrowserEvent` -Objekt als Parameter.
### InAppBrowserEvent Eigenschaften
* **Typ**: Eventname, entweder `loadstart` , `loadstop` , `loaderror` , oder `exit` . *(String)*
* **URL**: die URL, die geladen wurde. *(String)*
* **Code**: der Fehler-Code, nur im Fall von `loaderror` . *(Anzahl)*
* **Nachricht**: die Fehlermeldung angezeigt, nur im Fall von `loaderror` . *(String)*
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* iOS
* Windows 8 und 8.1
* Windows Phone 7 und 8
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Entfernt einen Listener für eine Veranstaltung aus der`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **Ref**: Bezugnahme auf die `InAppBrowser` Fenster. *(InAppBrowser)*
* **EventName**: das Ereignis zu warten. *(String)*
* **Loadstart**: Ereignis wird ausgelöst, wenn die `InAppBrowser` beginnt, eine URL zu laden.
* **Loadstop**: Ereignis wird ausgelöst, wenn der `InAppBrowser` beendet ist, eine URL laden.
* **LoadError**: Ereignis wird ausgelöst, wenn die `InAppBrowser` trifft einen Fehler beim Laden einer URLs.
* **Ausfahrt**: Ereignis wird ausgelöst, wenn das `InAppBrowser` -Fenster wird geschlossen.
* **Rückruf**: die Funktion ausgeführt, wenn das Ereignis ausgelöst wird. Die Funktion übergeben wird ein `InAppBrowserEvent` Objekt.
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* iOS
* Windows 8 und 8.1
* Windows Phone 7 und 8
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## Schließen
> Schließt die `InAppBrowser` Fenster.
ref.close();
* **Ref**: Bezugnahme auf die `InAppBrowser` Fenster *(InAppBrowser)*
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows 8 und 8.1
* Windows Phone 7 und 8
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## Karte
> Zeigt ein InAppBrowser-Fenster, das geöffnet wurde, versteckt. Aufrufen, dies hat keine Auswirkungen, wenn die InAppBrowser schon sichtbar war.
ref.show();
* **Ref**: Verweis auf die (InAppBrowser) Fenster`InAppBrowser`)
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* iOS
* Windows 8 und 8.1
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Fügt JavaScript-Code in das `InAppBrowser` Fenster
ref.executeScript(details, callback);
* **Ref**: Bezugnahme auf die `InAppBrowser` Fenster. *(InAppBrowser)*
* **InjectDetails**: Informationen über das Skript ausgeführt, angeben, entweder ein `file` oder `code` Schlüssel. *(Objekt)*
* **Datei**: URL des Skripts zu injizieren.
* **Code**: Text des Skripts zu injizieren.
* **Rückruf**: die Funktion, die ausgeführt wird, nachdem der JavaScript-Code injiziert wird.
* Wenn das eingefügte Skript vom Typ ist `code` , der Rückruf führt mit einen einzelnen Parameter, der der Rückgabewert des Skripts ist, umwickelt ein `Array` . Bei Multi-Line-Skripten ist der Rückgabewert von der letzten Anweisung oder den letzten Ausdruck ausgewertet.
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* iOS
* Windows 8 und 8.1
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
## insertCSS
> Injiziert CSS in der `InAppBrowser` Fenster.
ref.insertCSS(details, callback);
* **Ref**: Bezugnahme auf die `InAppBrowser` Fenster *(InAppBrowser)*
* **InjectDetails**: Informationen über das Skript ausgeführt, angeben, entweder ein `file` oder `code` Schlüssel. *(Objekt)*
* **Datei**: URL des Stylesheets zu injizieren.
* **Code**: Text des Stylesheets zu injizieren.
* **Rückruf**: die Funktion, die ausgeführt wird, nachdem die CSS injiziert wird.
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* iOS
### Kurzes Beispiel
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,388 +0,0 @@
<!--
# 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.
-->
# cordova-plugin-inappbrowser
[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)
Este plugin proporciona una vista de navegador web que se muestra cuando se llama a `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
El `cordova.InAppBrowser.open()` función se define como un reemplazo de sobreponer para la función `window.Open ()`. Llamadas existentes `window.Open ()` pueden utilizar la ventana InAppBrowser, mediante la sustitución de window.open:
window.open = cordova.InAppBrowser.open;
La ventana de InAppBrowser se comporta como un navegador web estándar y no puede acceder a Cordova APIs. Por este motivo, se recomienda la InAppBrowser si necesita cargar contenido de terceros (confianza), en lugar de que cargar en el principal webview Cordova. El InAppBrowser no está sujeta a la lista blanca, ni va a abrir enlaces en el navegador del sistema.
El InAppBrowser proporciona por defecto sus propios controles GUI para el usuario (atras, adelante, hacer).
Para atrás compatibilidad, este plugin también ganchos `window.open`. Sin embargo, el gancho de `window.open` plugin instalado puede tener efectos secundarios no deseados (especialmente si este plugin está incluido únicamente como una dependencia de otro plugin). El gancho de `window.open` se quitará en una versión futura de principal. Hasta que el gancho se ha extraído el plugin, aplicaciones pueden restaurar manualmente el comportamiento por defecto:
delete window.open // Reverts the call back to it's prototype's default
Aunque `window.open` es en el ámbito global, InAppBrowser no está disponible hasta después del evento `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Instalación
cordova plugin add cordova-plugin-inappbrowser
Si quieres todas las cargas de página en su aplicación para ir a través de la InAppBrowser, simplemente puedes conectar `window.open` durante la inicialización. Por ejemplo:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Se abre una dirección URL en una nueva instancia de `InAppBrowser`, en la instancia actual del navegador o el navegador del sistema.
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref**: referencia a la `InAppBrowser` ventana. *(InAppBrowser)*
* **url**: el URL para cargar *(String)*. Llame a `encodeURI()` en esto si la URL contiene caracteres Unicode.
* **target**: el objetivo en el que se carga la URL, un parámetro opcional que se utiliza de forma predeterminada `_self`. *(String)*
* `_self`: se abre en el Cordova WebView si la URL está en la lista blanca, de lo contrario se abre en el `InAppBrowser`.
* `_blank`: abre en el `InAppBrowser`.
* `_system`: se abre en el navegador del sistema.
* **options**: opciones para el `InAppBrowser`. Opcional, contumaz a: `location=yes`. *(String)*
La cadena de `options` no debe contener ningún espacio en blanco, y los pares de nombre y valor de cada característica deben estar separados por una coma. Los nombres de función son minúsculas. Todas las plataformas admiten el valor siguiente:
* **location**: se establece en `yes` o `no` para activar o desactivar la barra de ubicación de la `InAppBrowser`.
Sólo Android:
* **oculta**: a `yes` para crear el navegador y cargar la página, pero no lo demuestra. El evento loadstop se desencadena cuando termine la carga. Omitir o a `no` (por defecto) para que el navegador abra y carga normalmente.
* **clearcache**: a `yes` para que el navegador es caché de galleta despejado antes de que se abra la nueva ventana
* **clearsessioncache**: a `yes` que la caché de cookie de sesión despejado antes de que se abra la nueva ventana
* **zoom**: establezca en `sí` para mostrar los controles de zoom del navegador de Android, a `no` para ocultarlas. El valor predeterminado es `sí`.
* **hardwareback**: se establece en `sí` para utilizar el botón back de hardware para navegar hacia atrás a través de la historia de la `InAppBrowser`. Si no hay ninguna página anterior, se cerrará el `InAppBrowser` . El valor predeterminado es `sí`, por lo que se debe establecer en `no` si desea que el botón back para simplemente cerrar el InAppBrowser.
Sólo iOS:
* **closebuttoncaption**: establecer una cadena para usar como título del botón **hecho** . Tenga en cuenta que necesitas localizar este valor por sí mismo.
* **disallowoverscroll**: A `yes` o `no` (valor por defecto es `no` ). Activa/desactiva la propiedad UIWebViewBounce.
* **oculta**: a `yes` para crear el navegador y cargar la página, pero no lo demuestra. El evento loadstop se desencadena cuando termine la carga. Omitir o a `no` (por defecto) para que el navegador abra y carga normalmente.
* **clearcache**: a `yes` para que el navegador es caché de galleta despejado antes de que se abra la nueva ventana
* **clearsessioncache**: a `yes` que la caché de cookie de sesión despejado antes de que se abra la nueva ventana
* **barra de herramientas**: a `yes` o `no` para activar la barra de herramientas on u off para el InAppBrowser (por defecto`yes`)
* **enableViewportScale**: Set a `yes` o `no` para evitar viewport escalar a través de una etiqueta meta (por defecto a `no`).
* **mediaPlaybackRequiresUserAction**: Set a `yes` o `no` para evitar HTML5 audio o vídeo de reproducción automática (por defecto a `no`).
* **allowInlineMediaPlayback**: A `yes` o `no` para permitir la reproducción de los medios de comunicación en línea HTML5, mostrando en la ventana del navegador en lugar de una interfaz específica del dispositivo de reproducción. Elemento `video` de HTML también debe incluir el atributo de `webkit-playsinline` (por defecto a `no`)
* **keyboardDisplayRequiresUserAction**: se establece en `yes` o `no` para abrir el teclado cuando elementos de formulario reciben el foco mediante llamada de JavaScript de `focus()` (por defecto a `yes`).
* **suppressesIncrementalRendering**: se establece en `yes` o `no` para esperar hasta que todos los nuevos contenidos de vista se recibieron antes de ser prestados (por defecto a `no`).
* **presentationstyle**: se establece en `pagesheet`, `formsheet` o `fullscreen` para definir el [estilo de la presentación](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle) (por defecto a `fullscreen`).
* **transitionstyle**: se establece en `fliphorizontal`, `crossdissolve` o `coververtical` para definir el [estilo de transición](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle) (por defecto `coververtical`).
* **toolbarposition**: A `top` o `bottom` (valor por defecto es `bottom` ). Hace que la barra de herramientas en la parte superior o inferior de la ventana.
Sólo Windows:
* **oculta**: a `yes` para crear el navegador y cargar la página, pero no lo demuestra. El evento loadstop se desencadena cuando termine la carga. Omitir o a `no` (por defecto) para que el navegador abra y carga normalmente.
* **fullscreen**: se establece en `sí` para crear el control del navegador sin un borde alrededor de él. Por favor tenga en cuenta que si **location=no** también se especifica, no habrá ningún control presentado al usuario para cerrar la ventana IAB.
### Plataformas soportadas
* Amazon fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 y 8.1
* Windows Phone 7 y 8
* Explorador
### Ejemplo
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS rarezas
Como plugin no cumplir cualquier diseño es necesario añadir algunas reglas CSS si abre con `target = '_blank'`. Las reglas pueden parecerse a estos
```css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
```
### Windows rarezas
Similar al comportamiento visual de la ventana de Firefox OS IAB puede anularse mediante `inAppBrowserWrap`/`inAppBrowserWrapFullscreen` clases CSS
### Navegador rarezas
* Plugin se implementa mediante iframe,
* Historial de navegación (botones`atrás` y `adelante` en LocationBar) no está implementado.
## InAppBrowser
El objeto devuelto desde una llamada a `cordova.InAppBrowser.open`.
### Métodos
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> Añade un detector para un evento de la `InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ref**: referencia a la ventana de `InAppBrowser` *(InAppBrowser)*
* **eventName**: el evento para escuchar *(String)*
* **loadstart**: evento se desencadena cuando el `InAppBrowser` comienza a cargar una dirección URL.
* **loadstop**: evento desencadena cuando los acabados `InAppBrowser` cargar una dirección URL.
* **loaderror**: evento se desencadena cuando el `InAppBrowser` encuentra un error al cargar una dirección URL.
* **exit**: evento se desencadena cuando se cierra la ventana de `InAppBrowser`.
* **callback**: la función que se ejecuta cuando se desencadene el evento. La función se pasa un objeto `InAppBrowserEvent` como un parámetro.
### InAppBrowserEvent propiedades
* **type**: eventname, `loadstart`, `loadstop`, `loaderror` o `exit`. *(String)*
* **url**: la URL que se cargó. *(String)*
* **code**: el código de error, sólo en el caso de `loaderror`. *(Número)*
* **message**: el mensaje de error, sólo en el caso de `loaderror`. *(String)*
### Plataformas soportadas
* Amazon fire OS
* Android
* iOS
* Windows 8 y 8.1
* Windows Phone 7 y 8
* Explorador
### Navegador rarezas
eventos `loadstart` y `loaderror` no son alimentados.
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Elimina un detector para un evento de la `InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ref**: referencia a la ventana de `InAppBrowser`. *(InAppBrowser)*
* **eventName**: dejar de escuchar para el evento. *(String)*
* **loadstart**: evento se desencadena cuando el `InAppBrowser` comienza a cargar una dirección URL.
* **loadstop**: evento desencadena cuando los acabados `InAppBrowser` cargar una dirección URL.
* **loaderror**: evento se desencadena cuando el `InAppBrowser` se encuentra con un error al cargar una dirección URL.
* **exit**: evento se desencadena cuando se cierra la ventana de `InAppBrowser`.
* **callback**: la función a ejecutar cuando se desencadene el evento. La función se pasa un objeto `InAppBrowserEvent`.
### Plataformas soportadas
* Amazon fire OS
* Android
* iOS
* Windows 8 y 8.1
* Windows Phone 7 y 8
* Explorador
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> Cierra la ventana de `InAppBrowser`.
ref.close();
* **ref**: referencia a la ventana de `InAppBrowser` *(InAppBrowser)*
### Plataformas soportadas
* Amazon fire OS
* Android
* Firefox OS
* iOS
* Windows 8 y 8.1
* Windows Phone 7 y 8
* Explorador
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> Muestra una ventana InAppBrowser que abrió sus puertas ocultada. Esto no tiene efecto si el InAppBrowser ya era visible.
ref.show();
* **ref**: referencia a la (ventana) InAppBrowser`InAppBrowser`)
### Plataformas soportadas
* Amazon fire OS
* Android
* iOS
* Windows 8 y 8.1
* Explorador
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Inyecta código JavaScript en la ventana de `InAppBrowser`
ref.executeScript(details, callback);
* **ref**: referencia a la ventana de `InAppBrowser`. *(InAppBrowser)*
* **injectDetails**: detalles de la secuencia de comandos para ejecutar, o especificar un `file` o `code` clave. *(Objeto)*
* **file**: URL del script para inyectar.
* **code**: texto de la escritura para inyectar.
* **devolución de llamada**: la función que se ejecuta después de inyecta el código JavaScript.
* Si el script inyectado es del tipo de `code`, la devolución de llamada se ejecuta con un solo parámetro, que es el valor devuelto del guión, envuelto en una `Array`. Para scripts multilíneas, este es el valor devuelto de la última declaración, o la última expresión evaluada.
### Plataformas soportadas
* Amazon fire OS
* Android
* iOS
* Windows 8 y 8.1
* Explorador
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### Navegador rarezas
* sólo **code** es compatible.
### Windows rarezas
Debido a la [documentación MSDN](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx) el script invocado puede devolver únicamente valores de cadena, de lo contrario el parámetro, pasa al **callback** será `[null]`.
## insertCSS
> Inyecta CSS en la ventana de `InAppBrowser`.
ref.insertCSS(details, callback);
* **ref**: referencia a la ventana de `InAppBrowser` *(InAppBrowser)*
* **injectDetails**: detalles de la secuencia de comandos para ejecutar, o especificar un `file` o `code` clave. *(Objeto)*
* **file**: URL de la hoja de estilos para inyectar.
* **code**: texto de la hoja de estilos para inyectar.
* **callback**: la función que se ejecuta después de inyectar el CSS.
### Plataformas soportadas
* Amazon fire OS
* Android
* iOS
* Windows
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,357 +0,0 @@
<!---
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.
-->
# cordova-plugin-inappbrowser
Este plugin proporciona una vista de navegador web que se muestra cuando se llama a `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
El `cordova.InAppBrowser.open()` función se define como un reemplazo de sobreponer para la función `window.Open ()`. Llamadas existentes `window.Open ()` pueden utilizar la ventana InAppBrowser, mediante la sustitución de window.open:
window.open = cordova.InAppBrowser.open;
La ventana de InAppBrowser se comporta como un navegador web estándar y no puede acceder a Cordova APIs. Por este motivo, se recomienda la InAppBrowser si necesita cargar contenido de terceros (confianza), en lugar de que cargar en el principal webview Cordova. El InAppBrowser no está sujeta a la lista blanca, ni va a abrir enlaces en el navegador del sistema.
El InAppBrowser proporciona por defecto sus propios controles GUI para el usuario (atras, adelante, hacer).
Para atrás compatibilidad, este plugin también ganchos `window.open`. Sin embargo, el gancho de `window.open` plugin instalado puede tener efectos secundarios no deseados (especialmente si este plugin está incluido únicamente como una dependencia de otro plugin). El gancho de `window.open` se quitará en una versión futura de principal. Hasta que el gancho se ha extraído el plugin, aplicaciones pueden restaurar manualmente el comportamiento por defecto:
delete window.open // Reverts the call back to it's prototype's default
Aunque `window.open` es en el ámbito global, InAppBrowser no está disponible hasta después del evento `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Instalación
cordova plugin add cordova-plugin-inappbrowser
Si quieres todas las cargas de página en su aplicación para ir a través de la InAppBrowser, simplemente puedes conectar `window.open` durante la inicialización. Por ejemplo:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Se abre una dirección URL en una nueva instancia de `InAppBrowser`, en la instancia actual del navegador o el navegador del sistema.
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref**: referencia a la `InAppBrowser` ventana. *(InAppBrowser)*
* **url**: el URL para cargar *(String)*. Llame a `encodeURI()` en esto si la URL contiene caracteres Unicode.
* **target**: el objetivo en el que se carga la URL, un parámetro opcional que se utiliza de forma predeterminada `_self`. *(String)*
* `_self`: se abre en el Cordova WebView si la URL está en la lista blanca, de lo contrario se abre en el `InAppBrowser`.
* `_blank`: abre en el `InAppBrowser`.
* `_system`: se abre en el navegador del sistema.
* **options**: opciones para el `InAppBrowser`. Opcional, contumaz a: `location=yes`. *(String)*
La cadena de `options` no debe contener ningún espacio en blanco, y los pares de nombre y valor de cada característica deben estar separados por una coma. Los nombres de función son minúsculas. Todas las plataformas admiten el valor siguiente:
* **location**: se establece en `yes` o `no` para activar o desactivar la barra de ubicación de la `InAppBrowser`.
Sólo Android:
* **oculta**: a `yes` para crear el navegador y cargar la página, pero no lo demuestra. El evento loadstop se desencadena cuando termine la carga. Omitir o establecer en `no` (por defecto) para que el navegador abra y carga normalmente.
* **clearcache**: a `yes` para que el navegador es caché de galleta despejado antes de que se abra la nueva ventana
* **clearsessioncache**: a `yes` que la caché de cookie de sesión despejado antes de que se abra la nueva ventana
Sólo iOS:
* **closebuttoncaption**: establecer una cadena para usar como título del botón **hecho** . Tenga en cuenta que necesitas localizar este valor por sí mismo.
* **disallowoverscroll**: A `yes` o `no` (valor por defecto es `no` ). Activa/desactiva la propiedad UIWebViewBounce.
* **oculta**: a `yes` para crear el navegador y cargar la página, pero no lo demuestra. El evento loadstop se desencadena cuando termine la carga. Omitir o a `no` (por defecto) para que el navegador abra y carga normalmente.
* **clearcache**: a `yes` para que el navegador es caché de galleta despejado antes de que se abra la nueva ventana
* **clearsessioncache**: a `yes` que la caché de cookie de sesión despejado antes de que se abra la nueva ventana
* **barra de herramientas**: a `yes` o `no` para activar la barra de herramientas on u off para el InAppBrowser (por defecto`yes`)
* **enableViewportScale**: Set a `yes` o `no` para evitar viewport escalar a través de una etiqueta meta (por defecto a `no`).
* **mediaPlaybackRequiresUserAction**: Set a `yes` o `no` para evitar HTML5 audio o vídeo de reproducción automática (por defecto a `no`).
* **allowInlineMediaPlayback**: A `yes` o `no` para permitir la reproducción de los medios de comunicación en línea HTML5, mostrando en la ventana del navegador en lugar de una interfaz específica del dispositivo de reproducción. Elemento `video` de HTML también debe incluir el atributo de `webkit-playsinline` (por defecto a `no`)
* **keyboardDisplayRequiresUserAction**: se establece en `yes` o `no` para abrir el teclado cuando elementos de formulario reciben el foco mediante llamada de JavaScript de `focus()` (por defecto a `yes`).
* **suppressesIncrementalRendering**: se establece en `yes` o `no` para esperar hasta que todos los nuevos contenidos de vista se recibieron antes de ser prestados (por defecto a `no`).
* **presentationstyle**: se establece en `pagesheet`, `formsheet` o `fullscreen` para definir el [estilo de la presentación][1] (por defecto a `fullscreen`).
* **transitionstyle**: se establece en `fliphorizontal`, `crossdissolve` o `coververtical` para definir el [estilo de transición][2] (por defecto `coververtical`).
* **toolbarposition**: A `top` o `bottom` (valor por defecto es `bottom` ). Hace que la barra de herramientas en la parte superior o inferior de la ventana.
Sólo Windows:
* **oculta**: a `yes` para crear el navegador y cargar la página, pero no lo demuestra. El evento loadstop se desencadena cuando termine la carga. Omitir o a `no` (por defecto) para que el navegador abra y carga normalmente.
[1]: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle
[2]: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle
### Plataformas soportadas
* Amazon fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 y 8.1
* Windows Phone 7 y 8
### Ejemplo
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS rarezas
Como plugin no cumplir cualquier diseño es necesario añadir algunas reglas CSS si abre con `target = '_blank'`. Las reglas pueden parecerse a estos
css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
## InAppBrowser
El objeto devuelto desde una llamada a `cordova.InAppBrowser.open`.
### Métodos
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> Añade un detector para un evento de la `InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ref**: referencia a la ventana de `InAppBrowser` *(InAppBrowser)*
* **eventName**: el evento para escuchar *(String)*
* **loadstart**: evento se desencadena cuando el `InAppBrowser` comienza a cargar una dirección URL.
* **loadstop**: evento desencadena cuando los acabados `InAppBrowser` cargar una dirección URL.
* **loaderror**: evento se desencadena cuando el `InAppBrowser` encuentra un error al cargar una dirección URL.
* **exit**: evento se desencadena cuando se cierra la ventana de `InAppBrowser`.
* **callback**: la función que se ejecuta cuando se desencadene el evento. La función se pasa un objeto `InAppBrowserEvent` como un parámetro.
### InAppBrowserEvent propiedades
* **type**: eventname, `loadstart`, `loadstop`, `loaderror` o `exit`. *(String)*
* **url**: la URL que se cargó. *(String)*
* **code**: el código de error, sólo en el caso de `loaderror`. *(Número)*
* **message**: el mensaje de error, sólo en el caso de `loaderror`. *(String)*
### Plataformas soportadas
* Amazon fire OS
* Android
* iOS
* Windows 8 y 8.1
* Windows Phone 7 y 8
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Elimina un detector para un evento de la `InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ref**: referencia a la ventana de `InAppBrowser`. *(InAppBrowser)*
* **eventName**: dejar de escuchar para el evento. *(String)*
* **loadstart**: evento se desencadena cuando el `InAppBrowser` comienza a cargar una dirección URL.
* **loadstop**: evento desencadena cuando los acabados `InAppBrowser` cargar una dirección URL.
* **loaderror**: evento se desencadena cuando el `InAppBrowser` se encuentra con un error al cargar una dirección URL.
* **exit**: evento se desencadena cuando se cierra la ventana de `InAppBrowser`.
* **callback**: la función a ejecutar cuando se desencadene el evento. La función se pasa un objeto `InAppBrowserEvent`.
### Plataformas soportadas
* Amazon fire OS
* Android
* iOS
* Windows 8 y 8.1
* Windows Phone 7 y 8
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> Cierra la ventana de `InAppBrowser`.
ref.close();
* **ref**: referencia a la ventana de `InAppBrowser` *(InAppBrowser)*
### Plataformas soportadas
* Amazon fire OS
* Android
* Firefox OS
* iOS
* Windows 8 y 8.1
* Windows Phone 7 y 8
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> Muestra una ventana InAppBrowser que abrió sus puertas ocultada. Esto no tiene efecto si el InAppBrowser ya era visible.
ref.show();
* **ref**: referencia a la (ventana) InAppBrowser`InAppBrowser`)
### Plataformas soportadas
* Amazon fire OS
* Android
* iOS
* Windows 8 y 8.1
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Inyecta código JavaScript en la ventana de `InAppBrowser`
ref.executeScript(details, callback);
* **ref**: referencia a la ventana de `InAppBrowser`. *(InAppBrowser)*
* **injectDetails**: detalles de la secuencia de comandos para ejecutar, o especificar un `file` o `code` clave. *(Objeto)*
* **file**: URL del script para inyectar.
* **code**: texto de la escritura para inyectar.
* **devolución de llamada**: la función que se ejecuta después de inyecta el código JavaScript.
* Si el script inyectado es del tipo de `code`, la devolución de llamada se ejecuta con un solo parámetro, que es el valor devuelto del guión, envuelto en una `Array`. Para scripts multilíneas, este es el valor devuelto de la última declaración, o la última expresión evaluada.
### Plataformas soportadas
* Amazon fire OS
* Android
* iOS
* Windows 8 y 8.1
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
## insertCSS
> Inyecta CSS en la ventana de `InAppBrowser`.
ref.insertCSS(details, callback);
* **ref**: referencia a la ventana de `InAppBrowser` *(InAppBrowser)*
* **injectDetails**: detalles de la secuencia de comandos para ejecutar, o especificar un `file` o `code` clave. *(Objeto)*
* **file**: URL de la hoja de estilos para inyectar.
* **code**: texto de la hoja de estilos para inyectar.
* **callback**: la función que se ejecuta después de inyectar el CSS.
### Plataformas soportadas
* Amazon fire OS
* Android
* iOS
### Ejemplo rápido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,388 +0,0 @@
<!--
# 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.
-->
# cordova-plugin-inappbrowser
[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)
Ce module fournit une vue de navigateur web qui s'affiche lorsque vous appelez `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
Le `cordova.InAppBrowser.open()` fonction est définie pour être un remplacement rapide de la fonction `window.open()`. Les appels existants `window.open()` peuvent utiliser la fenêtre de InAppBrowser, en remplaçant window.open :
window.open = cordova.InAppBrowser.open;
La fenêtre de InAppBrowser se comporte comme un navigateur web standard et ne peut pas accéder aux APIs Cordova. Pour cette raison, le InAppBrowser est recommandé si vous devez charger le contenu de tiers (non approuvé), au lieu de chargement que dans le principaux webview Cordova. Le InAppBrowser n'est pas soumis à la liste blanche, ni s'ouvre les liens dans le navigateur de système.
Le InAppBrowser fournit par défaut ses propres contrôles de GUI pour l'utilisateur (arrière, avant, fait).
Pour vers l'arrière la compatibilité, ce plugin crochets également `window.open`. Cependant, le plugin installé crochet de `window.open` peut avoir des effets secondaires involontaires (surtout si ce plugin est inclus uniquement comme une dépendance d'un autre plugin). Le crochet de `window.open` sera supprimé dans une future version majeure. Jusqu'à ce que le crochet est supprimé de la plugin, apps peuvent restaurer manuellement le comportement par défaut :
delete window.open // Reverts the call back to it's prototype's default
Bien que `window.open` est dans la portée globale, InAppBrowser n'est pas disponible jusqu'à ce qu'après l'événement `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Installation
cordova plugin add cordova-plugin-inappbrowser
Si vous souhaitez que toutes les charges de la page dans votre application de passer par le InAppBrowser, vous pouvez simplement accrocher `window.open` pendant l'initialisation. Par exemple :
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Ouvre une URL dans une nouvelle instance de `InAppBrowser`, l'instance de navigateur actuelle ou dans l'Explorateur du système.
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref** : référence à la fenêtre `InAppBrowser`. *(InAppBrowser)*
* **url** : l'URL à charger *(String)*. À encoder au préalable via `encodeURI()` si celle-ci contient des caractères Unicode.
* **target** : la cible du chargement de l'URL, ce paramètre est optionnel, sa valeur par défaut est `_self`. *(String)*
* `_self` : dirige le chargement vers la WebView Cordova si l'URL figure dans la liste blanche, sinon dans une fenêtre `InAppBrowser`.
* `_blank` : dirige le chargement vers une fenêtre `InAppBrowser`.
* `_system` : dirige le chargement vers le navigateur Web du système.
* **options** : permet de personnaliser la fenêtre `InAppBrowser`. Paramètre facultatif dont la valeur par défaut est `location=yes`. *(String)*
La chaîne `options` ne doit contenir aucun caractère vide, chaque paire nom/valeur représentant une fonctionnalité doit être séparée de la précédente par une virgule. Les noms de fonctionnalités sont sensibles à la casse. Toutes les plates-formes prennent en charge la valeur ci-dessous :
* **location** : régler à `yes` ou `no` afin d'afficher ou masquer la barre d'adresse de la fenêtre `InAppBrowser`.
Android uniquement :
* **caché**: la valeur `yes` pour créer le navigateur et charger la page, mais ne pas le montrer. L'événement loadstop est déclenché lorsque le chargement est terminé. Omettre ou la valeur `no` (par défaut) pour que le navigateur ouvrir et charger normalement.
* **ClearCache**: la valeur `yes` pour que le navigateur du cache de cookie effacé, avant l'ouverture de la nouvelle fenêtre
* **clearsessioncache**: la valeur `yes` pour avoir le cache de cookie de session autorisé avant l'ouverture de la nouvelle fenêtre
* **zoom**: la valeur `yes` pour afficher les commandes de zoom du navigateur Android, affectez `no` de les cacher. Valeur par défaut est `yes`.
* **hardwareback**: utilisez le bouton de retour de matériel pour naviguer vers l'arrière à travers l'histoire de `InAppBrowser`de la valeur `Oui` . S'il n'y a aucune page précédente, `InAppBrowser` fermera. La valeur par défaut est `yes`, alors vous devez le définir à `no` si vous souhaitez que le bouton back de simplement fermer la InAppBrowser.
iOS uniquement :
* **closebuttoncaption**: affectez une chaîne à utiliser comme la **fait** légende du bouton. Notez que vous devrez localiser cette valeur vous-même.
* **disallowoverscroll**: la valeur `yes` ou `no` (valeur par défaut est `no` ). Active/désactive la propriété UIWebViewBounce.
* **caché**: la valeur `yes` pour créer le navigateur et charger la page, mais ne pas le montrer. L'événement loadstop est déclenché lorsque le chargement est terminé. Omettre ou la valeur `no` (par défaut) pour que le navigateur ouvrir et charger normalement.
* **ClearCache**: la valeur `yes` pour que le navigateur du cache de cookie effacé, avant l'ouverture de la nouvelle fenêtre
* **clearsessioncache**: la valeur `yes` pour avoir le cache de cookie de session autorisé avant l'ouverture de la nouvelle fenêtre
* **barre d'outils**: la valeur `yes` ou `no` pour activer la barre d'outils ou désactiver pour le InAppBrowser (par défaut,`yes`)
* **enableViewportScale**: la valeur `yes` ou `no` pour empêcher la fenêtre de mise à l'échelle par une balise meta (par défaut,`no`).
* **mediaPlaybackRequiresUserAction**: la valeur `yes` ou `no` pour empêcher le HTML5 audio ou vidéo de la lecture automatique (par défaut,`no`).
* **allowInlineMediaPlayback**: la valeur `yes` ou `no` pour permettre la lecture du média en ligne HTML5, affichage dans la fenêtre du navigateur plutôt que d'une interface de lecture spécifique au périphérique. L'HTML `video` élément doit également inclure la `webkit-playsinline` attribut (par défaut,`no`)
* **keyboardDisplayRequiresUserAction**: la valeur `yes` ou `no` pour ouvrir le clavier lorsque les éléments reçoivent le focus par l'intermédiaire de JavaScript `focus()` appel (par défaut,`yes`).
* **suppressesIncrementalRendering**: la valeur `yes` ou `no` d'attendre que toutes les nouveautés de vue sont reçue avant d'être restitué (par défaut,`no`).
* **presentationstyle**: la valeur `pagesheet` , `formsheet` ou `fullscreen` pour définir le [style de présentation](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle) (par défaut,`fullscreen`).
* **transitionstyle**: la valeur `fliphorizontal` , `crossdissolve` ou `coververtical` pour définir le [style de transition](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle) (par défaut,`coververtical`).
* **toolbarposition**: la valeur `top` ou `bottom` (valeur par défaut est `bottom` ). Causes de la barre d'outils être en haut ou en bas de la fenêtre.
Windows uniquement :
* **caché**: la valeur `yes` pour créer le navigateur et charger la page, mais ne pas le montrer. L'événement loadstop est déclenché lorsque le chargement est terminé. Omettre ou la valeur `no` (par défaut) pour que le navigateur ouvrir et charger normalement.
* **fullscreen**: défini à `yes` pour créer le contrôle de navigateur sans bordure autour d'elle. Veuillez noter que si **location=no** est également spécifiée, il n'y n'aura aucun contrôle a présenté à l'utilisateur de fermer la fenêtre du CCI.
### Plates-formes supportées
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 et 8.1
* Windows Phone 7 et 8
* Navigateur
### Exemple
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS Quirks
Comme plugin n'est pas appliquer n'importe quelle conception il est nécessaire d'ajouter quelques règles CSS si ouvert avec `target= _blank`. Les règles pourraient ressembler à ces
```css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
```
### Bizarreries de Windows
Semblable à un comportement visuel fenêtre Firefox OS CCI peut être substituée par l'intermédiaire de `inAppBrowserWrap`/`inAppBrowserWrapFullscreen` des classes CSS
### Bizarreries navigateur
* Plugin est implémentée via iframe,
* Historique de navigation (boutons`back` et `forward` dans LocationBar) n'est pas implémentée.
## InAppBrowser
L'objet retourné par un appel à `cordova.InAppBrowser.open`.
### Méthodes
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> Ajoute un écouteur pour un évènement de la fenêtre `InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ref** : référence à la fenêtre `InAppBrowser`. *(InAppBrowser)*
* **eventname** : l'évènement à écouter *(String)*
* **loadstart** : évènement déclenché lorsque le chargement d'une URL débute dans la fenêtre `InAppBrowser`.
* **loadstop** : évènement déclenché lorsque la fenêtre `InAppBrowser` finit de charger une URL.
* **loaderror** : évènement déclenché si la fenêtre `InAppBrowser` rencontre une erreur lors du chargement d'une URL.
* **exit** : évènement déclenché lorsque la fenêtre `InAppBrowser` est fermée.
* **callback** : la fonction à exécuter lorsque l'évènement se déclenche. Un objet `InAppBrowserEvent` lui est transmis comme paramètre.
### Propriétés de InAppBrowserEvent
* **type** : le nom de l'évènement, soit `loadstart`, `loadstop`, `loaderror` ou `exit`. *(String)*
* **url** : l'URL ayant été chargée. *(String)*
* **code** : le code d'erreur, seulement pour `loaderror`. *(Number)*
* **message** : un message d'erreur, seulement pour `loaderror`. *(String)*
### Plates-formes supportées
* Amazon Fire OS
* Android
* iOS
* Windows 8 et 8.1
* Windows Phone 7 et 8
* Navigateur
### Bizarreries navigateur
les événements `loadstart` et `loaderror` ne sont pas déclenchés.
### Exemple court
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Supprime un écouteur pour un évènement de la fenêtre `InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ref** : référence à la fenêtre `InAppBrowser`. *(InAppBrowser)*
* **eventname** : l'évènement pour lequel arrêter l'écoute. *(String)*
* **loadstart** : évènement déclenché lorsque le chargement d'une URL débute dans la fenêtre `InAppBrowser`.
* **loadstop** : évènement déclenché lorsque la fenêtre `InAppBrowser` finit de charger une URL.
* **loaderror** : évènement déclenché si la fenêtre `InAppBrowser` rencontre une erreur lors du chargement d'une URL.
* **exit** : évènement déclenché lorsque la fenêtre `InAppBrowser` est fermée.
* **callback** : la fonction à exécuter lorsque l'évènement se déclenche. Un objet `InAppBrowserEvent` lui est transmis comme paramètre.
### Plates-formes supportées
* Amazon Fire OS
* Android
* iOS
* Windows 8 et 8.1
* Windows Phone 7 et 8
* Navigateur
### Exemple court
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> Ferme la fenêtre `InAppBrowser`.
ref.close();
* **ref** : référence à la fenêtre `InAppBrowser`. *(InAppBrowser)*
### Plates-formes supportées
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows 8 et 8.1
* Windows Phone 7 et 8
* Navigateur
### Exemple court
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> Affiche une fenêtre InAppBrowser qui a été ouverte cachée. Appeler cette méthode n'a aucun effet si la fenêtre en question est déjà visible.
ref.show();
* **Réf**: référence à la fenêtre () InAppBrowser`InAppBrowser`)
### Plates-formes supportées
* Amazon Fire OS
* Android
* iOS
* Windows 8 et 8.1
* Navigateur
### Exemple court
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Injecte du code JavaScript dans la fenêtre `InAppBrowser`
ref.executeScript(details, callback);
* **ref** : référence à la fenêtre `InAppBrowser`. *(InAppBrowser)*
* **injectDetails** : détails du script à exécuter, requérant une propriété `file` ou `code`. *(Object)*
* **file** : URL du script à injecter.
* **code** : texte du script à injecter.
* **callback** : une fonction exécutée après l'injection du code JavaScript.
* Si le script injecté est de type `code`, un seul paramètre est transmis à la fonction callback, correspondant à la valeur de retour du script enveloppée dans un `Array`. Pour les scripts multilignes, il s'agit de la valeur renvoyée par la dernière instruction ou la dernière expression évaluée.
### Plates-formes supportées
* Amazon Fire OS
* Android
* iOS
* Windows 8 et 8.1
* Navigateur
### Exemple court
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### Bizarreries navigateur
* clef de **code** uniquement est pris en charge.
### Bizarreries de Windows
En raison de la [documentation MSDN](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx) le script appelé peut retourner uniquement les valeurs de chaîne, sinon le paramètre, passé au **rappel** sera `[null]`.
## insertCSS
> Injecte des règles CSS dans la fenêtre `InAppBrowser`.
ref.insertCSS(details, callback);
* **ref** : référence à la fenêtre `InAppBrowser`. *(InAppBrowser)*
* **injectDetails** : détails du script à exécuter, requérant une propriété `file` ou `code`. *(Object)*
* **file** : URL de la feuille de style à injecter.
* **code** : contenu de la feuille de style à injecter.
* **callback** : une fonction exécutée après l'injection du fichier CSS.
### Plates-formes supportées
* Amazon Fire OS
* Android
* iOS
* Windows
### Exemple court
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,357 +0,0 @@
<!---
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.
-->
# cordova-plugin-inappbrowser
Ce module fournit une vue de navigateur web qui s'affiche lorsque vous appelez `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
Le `cordova.InAppBrowser.open()` fonction est définie pour être un remplacement rapide de la fonction `window.open()`. Les appels existants `window.open()` peuvent utiliser la fenêtre de InAppBrowser, en remplaçant window.open :
window.open = cordova.InAppBrowser.open;
La fenêtre de InAppBrowser se comporte comme un navigateur web standard et ne peut pas accéder aux APIs Cordova. Pour cette raison, le InAppBrowser est recommandé si vous devez charger le contenu de tiers (non approuvé), au lieu de chargement que dans le principaux webview Cordova. Le InAppBrowser n'est pas soumis à la liste blanche, ni s'ouvre les liens dans le navigateur de système.
Le InAppBrowser fournit par défaut ses propres contrôles de GUI pour l'utilisateur (arrière, avant, fait).
Pour vers l'arrière la compatibilité, ce plugin crochets également `window.open`. Cependant, le plugin installé crochet de `window.open` peut avoir des effets secondaires involontaires (surtout si ce plugin est inclus uniquement comme une dépendance d'un autre plugin). Le crochet de `window.open` sera supprimé dans une future version majeure. Jusqu'à ce que le crochet est supprimé de la plugin, apps peuvent restaurer manuellement le comportement par défaut :
delete window.open // Reverts the call back to it's prototype's default
Bien que `window.open` est dans la portée globale, InAppBrowser n'est pas disponible jusqu'à ce qu'après l'événement `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Installation
cordova plugin add cordova-plugin-inappbrowser
Si vous souhaitez que toutes les charges de la page dans votre application de passer par le InAppBrowser, vous pouvez simplement accrocher `window.open` pendant l'initialisation. Par exemple :
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Ouvre une URL dans une nouvelle instance de `InAppBrowser`, l'instance de navigateur actuelle ou dans l'Explorateur du système.
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref** : référence à la fenêtre `InAppBrowser`. *(InAppBrowser)*
* **url** : l'URL à charger *(String)*. À encoder au préalable via `encodeURI()` si celle-ci contient des caractères Unicode.
* **target** : la cible du chargement de l'URL, ce paramètre est optionnel, sa valeur par défaut est `_self`. *(String)*
* `_self` : dirige le chargement vers la WebView Cordova si l'URL figure dans la liste blanche, sinon dans une fenêtre `InAppBrowser`.
* `_blank` : dirige le chargement vers une fenêtre `InAppBrowser`.
* `_system` : dirige le chargement vers le navigateur Web du système.
* **options** : permet de personnaliser la fenêtre `InAppBrowser`. Paramètre facultatif dont la valeur par défaut est `location=yes`. *(String)*
La chaîne `options` ne doit contenir aucun caractère vide, chaque paire nom/valeur représentant une fonctionnalité doit être séparée de la précédente par une virgule. Les noms de fonctionnalités sont sensibles à la casse. Toutes les plates-formes prennent en charge la valeur ci-dessous :
* **location** : régler à `yes` ou `no` afin d'afficher ou masquer la barre d'adresse de la fenêtre `InAppBrowser`.
Android uniquement :
* **caché**: la valeur `yes` pour créer le navigateur et charger la page, mais ne pas le montrer. L'événement loadstop est déclenché lorsque le chargement est terminé. Omettre ou la valeur `no` (par défaut) pour que le navigateur ouvrir et charger normalement.
* **ClearCache**: la valeur `yes` pour que le navigateur du cache de cookie effacé, avant l'ouverture de la nouvelle fenêtre
* **clearsessioncache**: la valeur `yes` pour avoir le cache de cookie de session autorisé avant l'ouverture de la nouvelle fenêtre
iOS uniquement :
* **closebuttoncaption**: affectez une chaîne à utiliser comme la **fait** légende du bouton. Notez que vous devrez localiser cette valeur vous-même.
* **disallowoverscroll**: la valeur `yes` ou `no` (valeur par défaut est `no` ). Active/désactive la propriété UIWebViewBounce.
* **caché**: la valeur `yes` pour créer le navigateur et charger la page, mais ne pas le montrer. L'événement loadstop est déclenché lorsque le chargement est terminé. Omettre ou la valeur `no` (par défaut) pour que le navigateur ouvrir et charger normalement.
* **ClearCache**: la valeur `yes` pour que le navigateur du cache de cookie effacé, avant l'ouverture de la nouvelle fenêtre
* **clearsessioncache**: la valeur `yes` pour avoir le cache de cookie de session autorisé avant l'ouverture de la nouvelle fenêtre
* **barre d'outils**: la valeur `yes` ou `no` pour activer la barre d'outils ou désactiver pour le InAppBrowser (par défaut,`yes`)
* **enableViewportScale**: la valeur `yes` ou `no` pour empêcher la fenêtre de mise à l'échelle par une balise meta (par défaut,`no`).
* **mediaPlaybackRequiresUserAction**: la valeur `yes` ou `no` pour empêcher le HTML5 audio ou vidéo de la lecture automatique (par défaut,`no`).
* **allowInlineMediaPlayback**: la valeur `yes` ou `no` pour permettre la lecture du média en ligne HTML5, affichage dans la fenêtre du navigateur plutôt que d'une interface de lecture spécifique au périphérique. L'HTML `video` élément doit également inclure la `webkit-playsinline` attribut (par défaut,`no`)
* **keyboardDisplayRequiresUserAction**: la valeur `yes` ou `no` pour ouvrir le clavier lorsque les éléments reçoivent le focus par l'intermédiaire de JavaScript `focus()` appel (par défaut,`yes`).
* **suppressesIncrementalRendering**: la valeur `yes` ou `no` d'attendre que toutes les nouveautés de vue sont reçue avant d'être restitué (par défaut,`no`).
* **presentationstyle**: la valeur `pagesheet` , `formsheet` ou `fullscreen` pour définir le [style de présentation][1] (par défaut,`fullscreen`).
* **transitionstyle**: la valeur `fliphorizontal` , `crossdissolve` ou `coververtical` pour définir le [style de transition][2] (par défaut,`coververtical`).
* **toolbarposition**: la valeur `top` ou `bottom` (valeur par défaut est `bottom` ). Causes de la barre d'outils être en haut ou en bas de la fenêtre.
Windows uniquement :
* **caché**: la valeur `yes` pour créer le navigateur et charger la page, mais ne pas le montrer. L'événement loadstop est déclenché lorsque le chargement est terminé. Omettre ou la valeur `no` (par défaut) pour que le navigateur ouvrir et charger normalement.
[1]: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle
[2]: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 et 8.1
* Windows Phone 7 et 8
### Exemple
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS Quirks
Comme plugin n'est pas appliquer n'importe quelle conception il est nécessaire d'ajouter quelques règles CSS si ouvert avec `target= _blank`. Les règles pourraient ressembler à ces
css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
## InAppBrowser
L'objet retourné par un appel à `cordova.InAppBrowser.open`.
### Méthodes
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> Ajoute un écouteur pour un évènement de la fenêtre `InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ref** : référence à la fenêtre `InAppBrowser`. *(InAppBrowser)*
* **eventname** : l'évènement à écouter *(String)*
* **loadstart** : évènement déclenché lorsque le chargement d'une URL débute dans la fenêtre `InAppBrowser`.
* **loadstop** : évènement déclenché lorsque la fenêtre `InAppBrowser` finit de charger une URL.
* **loaderror** : évènement déclenché si la fenêtre `InAppBrowser` rencontre une erreur lors du chargement d'une URL.
* **exit** : évènement déclenché lorsque la fenêtre `InAppBrowser` est fermée.
* **callback** : la fonction à exécuter lorsque l'évènement se déclenche. Un objet `InAppBrowserEvent` lui est transmis comme paramètre.
### Propriétés de InAppBrowserEvent
* **type** : le nom de l'évènement, soit `loadstart`, `loadstop`, `loaderror` ou `exit`. *(String)*
* **url** : l'URL ayant été chargée. *(String)*
* **code** : le code d'erreur, seulement pour `loaderror`. *(Number)*
* **message** : un message d'erreur, seulement pour `loaderror`. *(String)*
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* iOS
* Windows 8 et 8.1
* Windows Phone 7 et 8
### Petit exemple
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Supprime un écouteur pour un évènement de la fenêtre `InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ref** : référence à la fenêtre `InAppBrowser`. *(InAppBrowser)*
* **eventname** : l'évènement pour lequel arrêter l'écoute. *(String)*
* **loadstart**: événement déclenche quand le `InAppBrowser` commence à charger une URL.
* **loadstop**: événement déclenche lorsque la `InAppBrowser` finit de charger une URL.
* **loaderror** : évènement déclenché si la fenêtre `InAppBrowser` rencontre une erreur lors du chargement d'une URL.
* **sortie**: événement déclenche quand le `InAppBrowser` fenêtre est fermée.
* **callback** : la fonction à exécuter lorsque l'évènement se déclenche. Un objet `InAppBrowserEvent` lui est transmis comme paramètre.
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* iOS
* Windows 8 et 8.1
* Windows Phone 7 et 8
### Petit exemple
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> Ferme la fenêtre `InAppBrowser`.
ref.close();
* **Réf**: référence à la `InAppBrowser` fenêtre *(InAppBrowser)*
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows 8 et 8.1
* Windows Phone 7 et 8
### Petit exemple
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> Affiche une fenêtre InAppBrowser qui a été ouverte cachée. Appeler cette méthode n'a aucun effet si la fenêtre en question est déjà visible.
ref.show();
* **Réf**: référence à la fenêtre () InAppBrowser`InAppBrowser`)
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* iOS
* Windows 8 et 8.1
### Petit exemple
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Injecte du code JavaScript dans la fenêtre `InAppBrowser`
ref.executeScript(details, callback);
* **Réf**: référence à la `InAppBrowser` fenêtre. *(InAppBrowser)*
* **injectDetails** : détails du script à exécuter, requérant une propriété `file` ou `code`. *(Object)*
* **file** : URL du script à injecter.
* **code** : texte du script à injecter.
* **callback** : une fonction exécutée après l'injection du code JavaScript.
* Si le script injecté est de type `code`, un seul paramètre est transmis à la fonction callback, correspondant à la valeur de retour du script enveloppée dans un `Array`. Pour les scripts multilignes, il s'agit de la valeur renvoyée par la dernière instruction ou la dernière expression évaluée.
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* iOS
* Windows 8 et 8.1
### Petit exemple
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
## insertCSS
> Injecte des règles CSS dans la fenêtre `InAppBrowser`.
ref.insertCSS(details, callback);
* **Réf**: référence à la `InAppBrowser` fenêtre *(InAppBrowser)*
* **injectDetails**: Détails du script à exécuter, spécifiant soit un `file` ou `code` clés. *(Objet)*
* **file** : URL de la feuille de style à injecter.
* **code** : contenu de la feuille de style à injecter.
* **callback** : une fonction exécutée après l'injection du fichier CSS.
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* iOS
### Petit exemple
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,388 +0,0 @@
<!--
# 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.
-->
# cordova-plugin-inappbrowser
[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)
Questo plugin fornisce una vista di browser web che viene visualizzato quando si chiama `di cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
Il `cordova.InAppBrowser.open()` funzione è definita per essere un rimpiazzo per la funzione `window.open`. Esistenti chiamate `Window` possono utilizzare la finestra di InAppBrowser, sostituendo window.open():
window.open = cordova.InAppBrowser.open;
La finestra di InAppBrowser si comporta come un browser web standard e non può accedere a Cordova APIs. Per questo motivo, è consigliabile la InAppBrowser se è necessario caricare il contenuto (non attendibile) di terze parti, invece di caricamento che in webview Cordova principale. Il InAppBrowser non è soggetto alla whitelist, né sta aprendo il link nel browser di sistema.
La InAppBrowser fornisce di default propri controlli GUI per l'utente (indietro, avanti, fatto).
Per indietro la compatibilità, questo plugin ganci anche `window.open`. Tuttavia, il plugin installato gancio di `window.open` può avere effetti collaterali indesiderati (soprattutto se questo plugin è incluso solo come dipendenza di un altro plugin). Il gancio di `window. open` verrà rimosso in una futura release principale. Fino a quando il gancio è rimosso dal plugin, apps può ripristinare manualmente il comportamento predefinito:
delete window.open // Reverts the call back to it's prototype's default
Sebbene `window.open` sia in ambito globale, InAppBrowser non è disponibile fino a dopo l'evento `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Installazione
cordova plugin add cordova-plugin-inappbrowser
Se si desidera che tutti i carichi di pagina nell'app di passare attraverso il InAppBrowser, si può semplicemente collegare `window.open` durante l'inizializzazione. Per esempio:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Apre un URL in una nuova istanza di `InAppBrowser`, l'istanza corrente del browser o il browser di sistema.
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref**: fare riferimento alla `InAppBrowser` finestra. *(InAppBrowser)*
* **url**: l'URL da caricare *(String)*. Chiamare `encodeURI()` su questo, se l'URL contiene caratteri Unicode.
* **target**: la destinazione in cui caricare l'URL, un parametro facoltativo che il valore predefinito è `_self` . *(String)*
* `_self`: Si apre in Cordova WebView se l'URL è nella lista bianca, altrimenti si apre nella`InAppBrowser`.
* `_blank`: Apre il`InAppBrowser`.
* `_system`: Si apre nel browser web del sistema.
* **options**: opzioni per il `InAppBrowser` . Opzionale, inadempiente a: `location=yes` . *(String)*
Il `options` stringa non deve contenere alcun spazio vuoto, e coppie nome/valore ogni funzionalità devono essere separate da una virgola. Caratteristica nomi sono tra maiuscole e minuscole. Tutte le piattaforme supportano il valore riportato di seguito:
* **posizione**: impostata su `yes` o `no` per trasformare il `InAppBrowser` di barra di posizione on o off.
Solo su Android:
* **nascosti**: impostare su `yes` per creare il browser e caricare la pagina, ma non mostrarlo. L'evento loadstop viene generato quando il caricamento è completato. Omettere o impostata su `no` (impostazione predefinita) per avere il browser aperto e caricare normalmente.
* **ClearCache**: impostare su `yes` per avere il browser cache cookie ha lasciata prima dell'apertura della nuova finestra
* **clearsessioncache**: impostare su `yes` per avere la cache cookie di sessione cancellata prima dell'apertura della nuova finestra
* **zoom**: impostare su `yes` per mostrare i controlli di zoom del browser Android, impostata su `no` per nasconderli. Valore predefinito è `yes`.
* **hardwareback**: impostare `yes` per utilizzare il pulsante Indietro hardware per spostarsi all'indietro tra il `InAppBrowser`di storia. Se esiste una pagina precedente, si chiuderà il `InAppBrowser` . Il valore predefinito è `yes`, quindi è necessario impostare a `no` , se si desidera che il pulsante indietro per chiudere semplicemente il InAppBrowser.
solo iOS:
* **closebuttoncaption**: impostare una stringa da utilizzare come didascalia del pulsante **fatto** . Si noti che è necessario localizzare questo valore a te stesso.
* **disallowoverscroll**: impostare su `yes` o `no` (default è `no` ). Attiva/disattiva la proprietà UIWebViewBounce.
* **nascosti**: impostare su `yes` per creare il browser e caricare la pagina, ma non mostrarlo. L'evento loadstop viene generato quando il caricamento è completato. Omettere o impostata su `no` (impostazione predefinita) per avere il browser aperto e caricare normalmente.
* **ClearCache**: impostare su `yes` per avere il browser cache cookie ha lasciata prima dell'apertura della nuova finestra
* **clearsessioncache**: impostare su `yes` per avere la cache cookie di sessione cancellata prima dell'apertura della nuova finestra
* **Toolbar**: impostare su `yes` o `no` per attivare la barra degli strumenti o disattivare per il InAppBrowser (default`yes`)
* **enableViewportScale**: impostare su `yes` o `no` per impedire la viewport ridimensionamento tramite un tag meta (default`no`).
* **mediaPlaybackRequiresUserAction**: impostare su `yes` o `no` per impedire HTML5 audio o video da AutoPlay (default`no`).
* **allowInlineMediaPlayback**: impostare su `yes` o `no` per consentire la riproduzione dei supporti HTML5 in linea, visualizzare all'interno della finestra del browser, piuttosto che un'interfaccia specifica del dispositivo di riproduzione. L'HTML `video` elemento deve includere anche il `webkit-playsinline` (default di attributo`no`)
* **keyboardDisplayRequiresUserAction**: impostare su `yes` o `no` per aprire la tastiera quando elementi form ricevano lo stato attivo tramite di JavaScript `focus()` chiamata (default`yes`).
* **suppressesIncrementalRendering**: impostare su `yes` o `no` aspettare fino a quando tutti i nuovi contenuti di vista viene ricevuto prima il rendering (default`no`).
* **presentationstyle**: impostare su `pagesheet` , `formsheet` o `fullscreen` per impostare lo [stile di presentazione](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle) (default`fullscreen`).
* **transitionstyle**: impostare su `fliphorizontal` , `crossdissolve` o `coververtical` per impostare lo [stile di transizione](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle) (default`coververtical`).
* **toolbarposition**: impostare su `top` o `bottom` (default è `bottom` ). Provoca la barra degli strumenti sia nella parte superiore o inferiore della finestra.
Solo per Windows:
* **nascosti**: impostare su `yes` per creare il browser e caricare la pagina, ma non mostrarlo. L'evento loadstop viene generato quando il caricamento è completato. Omettere o impostata su `no` (impostazione predefinita) per avere il browser aperto e caricare normalmente.
* **fullscreen**: impostata su `yes` per creare il controllo browser senza un bordo attorno ad esso. Siete pregati di notare che se **location=no** viene specificato, non ci sarà nessun controllo presentato all'utente per chiudere la finestra IAB.
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 e 8.1
* Windows Phone 7 e 8
* Browser
### Esempio
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS stranezze
Come plugin non imporre alcun disegno c'è bisogno di aggiungere alcune regole CSS se aperto con `target='_blank'`. Le regole potrebbero apparire come questi
```css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
```
### Stranezze di Windows
Simile al comportamento visivo finestra di Firefox OS IAB può essere sottoposto a override tramite `inAppBrowserWrap`/ classi CSS`inAppBrowserWrapFullscreen`
### Stranezze browser
* Plugin viene implementato tramite iframe,
* Cronologia di navigazione (pulsanti`indietro` e `Avanti` in LocationBar) non è implementato.
## InAppBrowser
L'oggetto restituito da una chiamata a `di cordova.InAppBrowser.open`.
### Metodi
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> Aggiunge un listener per un evento dal`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **Rif**: fare riferimento alla `InAppBrowser` finestra *(InAppBrowser)*
* **EventName**: l'evento per l'ascolto *(String)*
* **loadstart**: evento viene generato quando il `InAppBrowser` comincia a caricare un URL.
* **loadstop**: evento viene generato quando il `InAppBrowser` termina il caricamento di un URL.
* **LoadError**: evento viene generato quando il `InAppBrowser` rileva un errore durante il caricamento di un URL.
* **uscita**: evento viene generato quando il `InAppBrowser` finestra è chiusa.
* **richiamata**: la funzione che viene eseguito quando viene generato l'evento. La funzione viene passata un `InAppBrowserEvent` oggetto come parametro.
### Proprietà InAppBrowserEvent
* **tipo**: il eventname, o `loadstart` , `loadstop` , `loaderror` , o `exit` . *(String)*
* **URL**: l'URL che è stato caricato. *(String)*
* **codice**: il codice di errore, solo nel caso di `loaderror` . *(Numero)*
* **messaggio**: il messaggio di errore, solo nel caso di `loaderror` . *(String)*
### Piattaforme supportate
* Amazon fuoco OS
* Android
* iOS
* Windows 8 e 8.1
* Windows Phone 7 e 8
* Browser
### Stranezze browser
eventi `onloadstart` e `loaderror` non sono stati licenziati.
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Rimuove un listener per un evento dal`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **Rif**: fare riferimento alla `InAppBrowser` finestra. *(InAppBrowser)*
* **EventName**: interrompere l'attesa per l'evento. *(String)*
* **loadstart**: evento viene generato quando il `InAppBrowser` comincia a caricare un URL.
* **loadstop**: evento viene generato quando il `InAppBrowser` termina il caricamento di un URL.
* **LoadError**: evento viene generato quando il `InAppBrowser` rileva un errore di caricamento di un URL.
* **uscita**: evento viene generato quando il `InAppBrowser` finestra è chiusa.
* **richiamata**: la funzione da eseguire quando viene generato l'evento. La funzione viene passata un `InAppBrowserEvent` oggetto.
### Piattaforme supportate
* Amazon fuoco OS
* Android
* iOS
* Windows 8 e 8.1
* Windows Phone 7 e 8
* Browser
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> Chiude la `InAppBrowser` finestra.
ref.close();
* **Rif**: fare riferimento alla `InAppBrowser` finestra *(InAppBrowser)*
### Piattaforme supportate
* Amazon fuoco OS
* Android
* Firefox OS
* iOS
* Windows 8 e 8.1
* Windows Phone 7 e 8
* Browser
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> Visualizza una finestra di InAppBrowser che è stato aperto nascosta. Questa chiamata non ha effetto se la InAppBrowser era già visibile.
ref.show();
* **Rif**: riferimento per il InAppBrowser finestra (`InAppBrowser`)
### Piattaforme supportate
* Amazon fuoco OS
* Android
* iOS
* Windows 8 e 8.1
* Browser
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Inserisce il codice JavaScript nella `InAppBrowser` finestra
ref.executeScript(details, callback);
* **Rif**: fare riferimento alla `InAppBrowser` finestra. *(InAppBrowser)*
* **injectDetails**: dettagli dello script da eseguire, specificando un `file` o `code` chiave. *(Oggetto)*
* **file**: URL dello script da iniettare.
* **codice**: testo dello script da iniettare.
* **richiamata**: la funzione che viene eseguito dopo che il codice JavaScript viene iniettato.
* Se lo script iniettato è di tipo `code` , il callback viene eseguita con un singolo parametro, che è il valore restituito del copione, avvolto in un `Array` . Per gli script multi-linea, questo è il valore restituito dell'ultima istruzione, o l'ultima espressione valutata.
### Piattaforme supportate
* Amazon fuoco OS
* Android
* iOS
* Windows 8 e 8.1
* Browser
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### Stranezze browser
* è supportato solo il **code** chiave.
### Stranezze di Windows
A causa di [documenti MSDN](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx) lo script richiamato può restituire solo i valori di stringa, altrimenti il parametro, passato al **callback** sarà `[null]`.
## insertCSS
> Inietta CSS nella `InAppBrowser` finestra.
ref.insertCSS(details, callback);
* **Rif**: fare riferimento alla `InAppBrowser` finestra *(InAppBrowser)*
* **injectDetails**: dettagli dello script da eseguire, specificando un `file` o `code` chiave. *(Oggetto)*
* **file**: URL del foglio di stile per iniettare.
* **codice**: testo del foglio di stile per iniettare.
* **richiamata**: la funzione che viene eseguito dopo che il CSS viene iniettato.
### Piattaforme supportate
* Amazon fuoco OS
* Android
* iOS
* Windows
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,357 +0,0 @@
<!---
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.
-->
# cordova-plugin-inappbrowser
Questo plugin fornisce una vista di browser web che viene visualizzato quando si chiama `di cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
Il `cordova.InAppBrowser.open()` funzione è definita per essere un rimpiazzo per la funzione `window.open`. Esistenti chiamate `Window` possono utilizzare la finestra di InAppBrowser, sostituendo window.open():
window.open = cordova.InAppBrowser.open;
La finestra di InAppBrowser si comporta come un browser web standard e non può accedere a Cordova APIs. Per questo motivo, è consigliabile la InAppBrowser se è necessario caricare il contenuto (non attendibile) di terze parti, invece di caricamento che in webview Cordova principale. Il InAppBrowser non è soggetto alla whitelist, né sta aprendo il link nel browser di sistema.
La InAppBrowser fornisce di default propri controlli GUI per l'utente (indietro, avanti, fatto).
Per indietro la compatibilità, questo plugin ganci anche `window.open`. Tuttavia, il plugin installato gancio di `window.open` può avere effetti collaterali indesiderati (soprattutto se questo plugin è incluso solo come dipendenza di un altro plugin). Il gancio di `window. open` verrà rimosso in una futura release principale. Fino a quando il gancio è rimosso dal plugin, apps può ripristinare manualmente il comportamento predefinito:
delete window.open // Reverts the call back to it's prototype's default
Sebbene `window.open` sia in ambito globale, InAppBrowser non è disponibile fino a dopo l'evento `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Installazione
cordova plugin add cordova-plugin-inappbrowser
Se si desidera che tutti i carichi di pagina nell'app di passare attraverso il InAppBrowser, si può semplicemente collegare `window.open` durante l'inizializzazione. Per esempio:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Apre un URL in una nuova istanza di `InAppBrowser`, l'istanza corrente del browser o il browser di sistema.
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref**: fare riferimento alla `InAppBrowser` finestra. *(InAppBrowser)*
* **url**: l'URL da caricare *(String)*. Chiamare `encodeURI()` su questo, se l'URL contiene caratteri Unicode.
* **target**: la destinazione in cui caricare l'URL, un parametro facoltativo che il valore predefinito è `_self` . *(String)*
* `_self`: Si apre in Cordova WebView se l'URL è nella lista bianca, altrimenti si apre nella`InAppBrowser`.
* `_blank`: Apre il`InAppBrowser`.
* `_system`: Si apre nel browser web del sistema.
* **options**: opzioni per il `InAppBrowser` . Opzionale, inadempiente a: `location=yes` . *(String)*
Il `options` stringa non deve contenere alcun spazio vuoto, e coppie nome/valore ogni funzionalità devono essere separate da una virgola. Caratteristica nomi sono tra maiuscole e minuscole. Tutte le piattaforme supportano il valore riportato di seguito:
* **posizione**: impostata su `yes` o `no` per trasformare il `InAppBrowser` di barra di posizione on o off.
Solo su Android:
* **nascosti**: impostare su `yes` per creare il browser e caricare la pagina, ma non mostrarlo. L'evento loadstop viene generato quando il caricamento è completato. Omettere o impostata su `no` (impostazione predefinita) per avere il browser aperto e caricare normalmente.
* **ClearCache**: impostare su `yes` per avere il browser cache cookie ha lasciata prima dell'apertura della nuova finestra
* **clearsessioncache**: impostare su `yes` per avere la cache cookie di sessione cancellata prima dell'apertura della nuova finestra
solo iOS:
* **closebuttoncaption**: impostare una stringa da utilizzare come didascalia del pulsante **fatto** . Si noti che è necessario localizzare questo valore a te stesso.
* **disallowoverscroll**: impostare su `yes` o `no` (default è `no` ). Attiva/disattiva la proprietà UIWebViewBounce.
* **nascosti**: impostare su `yes` per creare il browser e caricare la pagina, ma non mostrarlo. L'evento loadstop viene generato quando il caricamento è completato. Omettere o impostata su `no` (impostazione predefinita) per avere il browser aperto e caricare normalmente.
* **ClearCache**: impostare su `yes` per avere il browser cache cookie ha lasciata prima dell'apertura della nuova finestra
* **clearsessioncache**: impostare su `yes` per avere la cache cookie di sessione cancellata prima dell'apertura della nuova finestra
* **Toolbar**: impostare su `yes` o `no` per attivare la barra degli strumenti o disattivare per il InAppBrowser (default`yes`)
* **enableViewportScale**: impostare su `yes` o `no` per impedire la viewport ridimensionamento tramite un tag meta (default`no`).
* **mediaPlaybackRequiresUserAction**: impostare su `yes` o `no` per impedire HTML5 audio o video da AutoPlay (default`no`).
* **allowInlineMediaPlayback**: impostare su `yes` o `no` per consentire la riproduzione dei supporti HTML5 in linea, visualizzare all'interno della finestra del browser, piuttosto che un'interfaccia specifica del dispositivo di riproduzione. L'HTML `video` elemento deve includere anche il `webkit-playsinline` (default di attributo`no`)
* **keyboardDisplayRequiresUserAction**: impostare su `yes` o `no` per aprire la tastiera quando elementi form ricevano lo stato attivo tramite di JavaScript `focus()` chiamata (default`yes`).
* **suppressesIncrementalRendering**: impostare su `yes` o `no` aspettare fino a quando tutti i nuovi contenuti di vista viene ricevuto prima il rendering (default`no`).
* **presentationstyle**: impostare su `pagesheet` , `formsheet` o `fullscreen` per impostare lo [stile di presentazione][1] (default`fullscreen`).
* **transitionstyle**: impostare su `fliphorizontal` , `crossdissolve` o `coververtical` per impostare lo [stile di transizione][2] (default`coververtical`).
* **toolbarposition**: impostare su `top` o `bottom` (default è `bottom` ). Provoca la barra degli strumenti sia nella parte superiore o inferiore della finestra.
Solo per Windows:
* **nascosti**: impostare su `yes` per creare il browser e caricare la pagina, ma non mostrarlo. L'evento loadstop viene generato quando il caricamento è completato. Omettere o impostata su `no` (impostazione predefinita) per avere il browser aperto e caricare normalmente.
[1]: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle
[2]: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 e 8.1
* Windows Phone 7 e 8
### Esempio
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS stranezze
Come plugin non imporre alcun disegno c'è bisogno di aggiungere alcune regole CSS se aperto con `target='_blank'`. Le regole potrebbero apparire come questi
css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
## InAppBrowser
L'oggetto restituito da una chiamata a `di cordova.InAppBrowser.open`.
### Metodi
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> Aggiunge un listener per un evento dal`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **Rif**: fare riferimento alla `InAppBrowser` finestra *(InAppBrowser)*
* **EventName**: l'evento per l'ascolto *(String)*
* **loadstart**: evento viene generato quando il `InAppBrowser` comincia a caricare un URL.
* **loadstop**: evento viene generato quando il `InAppBrowser` termina il caricamento di un URL.
* **LoadError**: evento viene generato quando il `InAppBrowser` rileva un errore durante il caricamento di un URL.
* **uscita**: evento viene generato quando il `InAppBrowser` finestra è chiusa.
* **richiamata**: la funzione che viene eseguito quando viene generato l'evento. La funzione viene passata un `InAppBrowserEvent` oggetto come parametro.
### Proprietà InAppBrowserEvent
* **tipo**: il eventname, o `loadstart` , `loadstop` , `loaderror` , o `exit` . *(String)*
* **URL**: l'URL che è stato caricato. *(String)*
* **codice**: il codice di errore, solo nel caso di `loaderror` . *(Numero)*
* **messaggio**: il messaggio di errore, solo nel caso di `loaderror` . *(String)*
### Piattaforme supportate
* Amazon fuoco OS
* Android
* iOS
* Windows 8 e 8.1
* Windows Phone 7 e 8
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Rimuove un listener per un evento dal`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **Rif**: fare riferimento alla `InAppBrowser` finestra. *(InAppBrowser)*
* **EventName**: interrompere l'attesa per l'evento. *(String)*
* **loadstart**: evento viene generato quando il `InAppBrowser` comincia a caricare un URL.
* **loadstop**: evento viene generato quando il `InAppBrowser` termina il caricamento di un URL.
* **LoadError**: evento viene generato quando il `InAppBrowser` rileva un errore di caricamento di un URL.
* **uscita**: evento viene generato quando il `InAppBrowser` finestra è chiusa.
* **richiamata**: la funzione da eseguire quando viene generato l'evento. La funzione viene passata un `InAppBrowserEvent` oggetto.
### Piattaforme supportate
* Amazon fuoco OS
* Android
* iOS
* Windows 8 e 8.1
* Windows Phone 7 e 8
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> Chiude la `InAppBrowser` finestra.
ref.close();
* **Rif**: fare riferimento alla `InAppBrowser` finestra *(InAppBrowser)*
### Piattaforme supportate
* Amazon fuoco OS
* Android
* Firefox OS
* iOS
* Windows 8 e 8.1
* Windows Phone 7 e 8
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> Visualizza una finestra di InAppBrowser che è stato aperto nascosta. Questa chiamata non ha effetto se la InAppBrowser era già visibile.
ref.show();
* **Rif**: riferimento per il InAppBrowser finestra (`InAppBrowser`)
### Piattaforme supportate
* Amazon fuoco OS
* Android
* iOS
* Windows 8 e 8.1
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Inserisce il codice JavaScript nella `InAppBrowser` finestra
ref.executeScript(details, callback);
* **Rif**: fare riferimento alla `InAppBrowser` finestra. *(InAppBrowser)*
* **injectDetails**: dettagli dello script da eseguire, specificando un `file` o `code` chiave. *(Oggetto)*
* **file**: URL dello script da iniettare.
* **codice**: testo dello script da iniettare.
* **richiamata**: la funzione che viene eseguito dopo che il codice JavaScript viene iniettato.
* Se lo script iniettato è di tipo `code` , il callback viene eseguita con un singolo parametro, che è il valore restituito del copione, avvolto in un `Array` . Per gli script multi-linea, questo è il valore restituito dell'ultima istruzione, o l'ultima espressione valutata.
### Piattaforme supportate
* Amazon fuoco OS
* Android
* iOS
* Windows 8 e 8.1
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
## insertCSS
> Inietta CSS nella `InAppBrowser` finestra.
ref.insertCSS(details, callback);
* **Rif**: fare riferimento alla `InAppBrowser` finestra *(InAppBrowser)*
* **injectDetails**: dettagli dello script da eseguire, specificando un `file` o `code` chiave. *(Oggetto)*
* **file**: URL del foglio di stile per iniettare.
* **codice**: testo del foglio di stile per iniettare.
* **richiamata**: la funzione che viene eseguito dopo che il CSS viene iniettato.
### Piattaforme supportate
* Amazon fuoco OS
* Android
* iOS
### Esempio rapido
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,388 +0,0 @@
<!--
# 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.
-->
# cordova-plugin-inappbrowser
[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)
このプラグインは `コルドバを呼び出すときに表示される web ブラウザーのビューを提供します。InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
`コルドバ。InAppBrowser.open()` `window.open()` 関数との交換を定義する関数。 既存の `window.open()` 呼び出しは、window.open を置き換えることによって InAppBrowser ウィンドウを使用できます。
window.open = cordova.InAppBrowser.open;
InAppBrowser ウィンドウは標準的な web ブラウザーのように動作し、コルドバ Api にアクセスできません。 この理由から、InAppBrowser お勧めする場合はメインのコルドバの webview を読み込むのではなくサード パーティ (信頼されていない) コンテンツをロードする必要があります。 InAppBrowser、ホワイト リストの対象ではないも、システムのブラウザーでリンクを開くです。
InAppBrowser を提供しますデフォルトで GUI コントロール (戻る、進む、行う)。
後方互換性、このプラグインは、また `window.open` をフックのため。 ただし、`window.open` のプラグイン インストール フックを持つことができます意図しない副作用 (特に場合は、このプラグインは別のプラグインの依存関係としてのみ含まれています)。 `window.open` のフックは、将来のメジャー リリースで削除されます。 プラグインから、フックが削除されるまでアプリはデフォルトの動作を手動で復元できます。
delete window.open // Reverts the call back to it's prototype's default
`window.open` はグローバル スコープでは、InAppBrowser は、`deviceready` イベントの後まで利用できません。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## インストール
cordova plugin add cordova-plugin-inappbrowser
InAppBrowser を通過するアプリですべてのページの読み込みをする場合は初期化中に `window.open` を単にフックできます。たとえば。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
新しい `InAppBrowser` インスタンスを現在のブラウザー インスタンスまたはシステムのブラウザーで URL を開きます。
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref**: への参照を `InAppBrowser` ウィンドウ。*(InAppBrowser)*
* **url**: *(文字列)*をロードする URL。電話 `encodeURI()` 場合は、この上の URL は Unicode 文字を含みます。
* **ターゲット**: ターゲット URL は、既定値は、省略可能なパラメーターをロードするを `_self` 。*(文字列)*
* `_self`: コルドバ WebView URL がホワイト リストにある場合で開きます、それ以外の場合で開きます、`InAppBrowser`.
* `_blank`: で開きます、`InAppBrowser`.
* `_system`: システムの web ブラウザーで開きます。
* **オプション**: おぷしょん、 `InAppBrowser` 。省略可能にする: `location=yes` 。*(文字列)*
`options`文字列にはする必要があります任意の空白スペースが含まれていないと、各機能の名前と値のペアをコンマで区切る必要があります。 機能名では大文字小文字を区別します。 以下の値をサポートするプラットフォーム。
* **場所** に設定 `yes` または `no` を有効にする、 `InAppBrowser` の場所バー オンまたはオフにします。
アンドロイドのみ:
* **非表示**: 設定 `yes` ブラウザーを作成して、ページの読み込みが表示されません。 Loadstop イベントは、読み込みが完了すると発生します。 省略するか設定 `no` (既定値) を開くし、通常読み込みブラウザーを持っています。
* **clearcache**: に設定されている `yes` 、ブラウザーのクッキー キャッシュ クリア新しいウィンドウが開く前に
* **clearsessioncache** に設定されている `yes` はセッション cookie のキャッシュをオフにすると、新しいウィンドウが開く前に
* **zoom**:`yes`Android ブラウザーのズーム コントロールの表示を`no`に設定すると、それらを非表示に設定します。 既定値は`yes`.
* **hardwareback**: `InAppBrowser`の履歴を後方に移動するのにハードウェアの戻るボタンを使用して`yes`に設定します。 前のページがない場合は、 `InAppBrowser`が終了します。 既定値は`はい`、ため場合は、単に、InAppBrowser を閉じる戻るボタン`なし`を設定する必要があります。
iOS のみ:
* **closebuttoncaption**: [**完了**] ボタンのキャプションとして使用する文字列に設定します。自分でこの値をローカライズする必要があることに注意してください。
* **disallowoverscroll** に設定されている `yes` または `no` (既定値は `no` )。/UIWebViewBounce プロパティをオフにします。
* **非表示**: 設定 `yes` ブラウザーを作成して、ページの読み込みが表示されません。 Loadstop イベントは、読み込みが完了すると発生します。 省略するか設定 `no` (既定値) を開くし、通常読み込みブラウザーを持っています。
* **clearcache**: に設定されている `yes` 、ブラウザーのクッキー キャッシュ クリア新しいウィンドウが開く前に
* **clearsessioncache** に設定されている `yes` はセッション cookie のキャッシュをオフにすると、新しいウィンドウが開く前に
* **ツールバー**: に設定されている `yes` または `no` InAppBrowser (デフォルトのツールバーのオンまたはオフを有効にするには`yes`)
* **enableViewportScale** に設定されている `yes` または `no` を (デフォルトではメタタグを介してスケーリング ビューポートを防ぐために`no`).
* **mediaPlaybackRequiresUserAction** に設定されている `yes` または `no` を HTML5 オーディオまたはビデオを自動再生 (初期設定から防ぐために`no`).
* **allowInlineMediaPlayback** に設定されている `yes` または `no` ラインで HTML5 メディア再生には、デバイス固有再生インターフェイスではなく、ブラウザー ウィンドウ内に表示するようにします。 HTML の `video` 要素を含める必要がありますまた、 `webkit-playsinline` 属性 (デフォルトは`no`)
* **keyboardDisplayRequiresUserAction** に設定されている `yes` または `no` をフォーム要素の JavaScript を介してフォーカスを受け取るときに、キーボードを開く `focus()` コール (デフォルトは`yes`).
* **suppressesIncrementalRendering** に設定されている `yes` または `no` (デフォルトでは表示される前にビューのすべての新しいコンテンツを受信するまで待機するには`no`).
* **presentationstyle** に設定されている `pagesheet``formsheet` または `fullscreen` (デフォルトでは、[プレゼンテーション スタイル](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle)を設定するには`fullscreen`).
* **transitionstyle** に設定されている `fliphorizontal``crossdissolve` または `coververtical` (デフォルトでは、[トランジションのスタイル](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle)を設定するには`coververtical`).
* **toolbarposition** に設定されている `top` または `bottom` (既定値は `bottom` )。上部またはウィンドウの下部にツールバーが発生します。
Windows のみ:
* **非表示**: 設定 `yes` ブラウザーを作成して、ページの読み込みが表示されません。 Loadstop イベントは、読み込みが完了すると発生します。 省略するか設定 `no` (既定値) を開くし、通常読み込みブラウザーを持っています。
* **fullscreen**: 周りに境界線なしブラウザー コントロールを作成する`[yes]`に設定します。 その場合に注意してください**location=no**指定また、IAB ウィンドウを閉じるためにユーザーに提示はコントロールされます。
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* Firefox の OS
* iOS
* Windows 8 および 8.1
* Windows Phone 7 と 8
* ブラウザー
### 例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS 癖
開かれた場合にいくつかの CSS ルールを追加する必要があるプラグインは任意のデザインを適用しないと `target ='_blank'`。これらのような規則になります。
```css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
```
### Windows の癖
`InAppBrowserWrap`経由で Firefox OS IAB ウィンドウの視覚的動作に似ていますをオーバーライドできます/`inAppBrowserWrapFullscreen` CSS クラス
### ブラウザーの癖
* Iframe を介してプラグインを実装します。
* ナビゲーション履歴 (LocationBar の`進む``戻る`ボタン) は実装されていません。
## InAppBrowser
`コルドバへの呼び出しから返されるオブジェクト。InAppBrowser.open`.
### メソッド
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> イベントのリスナーを追加します、`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ref**: への参照を `InAppBrowser` ウィンドウ*(InAppBrowser)*
* **eventname**: *(文字列)*をリッスンするイベント
* **** イベントが発生するとき、 `InAppBrowser` の URL の読み込みが開始します。
* **loadstop** イベントが発生するとき、 `InAppBrowser` URL の読み込みが完了します。
* **loaderror** イベントが発生するとき、 `InAppBrowser` URL の読み込みでエラーが発生します。
* **終了**: イベントが発生するとき、 `InAppBrowser` ウィンドウが閉じられます。
* **コールバック**: イベントが発生したときに実行される関数。関数に渡されますが、 `InAppBrowserEvent` オブジェクトをパラメーターとして。
### InAppBrowserEvent プロパティ
* **タイプ**: eventname どちらか `loadstart``loadstop``loaderror` 、または `exit` 。*(文字列)*
* **url**: URL が読み込まれました。*(文字列)*
* **コード**: の場合にのみ、エラー コード `loaderror` 。*(数)*
* **メッセージ**: の場合にのみ、エラー メッセージ `loaderror` 。*(文字列)*
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* iOS
* Windows 8 および 8.1
* Windows Phone 7 と 8
* ブラウザー
### ブラウザーの癖
`loadstart` `loaderror`イベントが発生していません。
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> イベントのリスナーを削除します、`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ref**: への参照を `InAppBrowser` ウィンドウ。*(InAppBrowser)*
* **eventname**: イベントのリッスンを停止します。*(文字列)*
* **** イベントが発生するとき、 `InAppBrowser` の URL の読み込みが開始します。
* **loadstop** イベントが発生するとき、 `InAppBrowser` URL の読み込みが完了します。
* **loaderror** イベントが発生するとき、 `InAppBrowser` URL の読み込みエラーが発生します。
* **終了**: イベントが発生するとき、 `InAppBrowser` ウィンドウが閉じられます。
* **コールバック**: イベントが発生するときに実行する関数。関数に渡されますが、 `InAppBrowserEvent` オブジェクト。
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* iOS
* Windows 8 および 8.1
* Windows Phone 7 と 8
* ブラウザー
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> 閉じる、 `InAppBrowser` ウィンドウ。
ref.close();
* **ref**: への参照を `InAppBrowser` ウィンドウ*(InAppBrowser)*
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* Firefox の OS
* iOS
* Windows 8 および 8.1
* Windows Phone 7 と 8
* ブラウザー
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> 隠された開かれた InAppBrowser ウィンドウが表示されます。この関数を呼び出すは影響しません、InAppBrowser が既に表示されている場合。
ref.show();
* **ref**: InAppBrowser ウィンドウ (への参照`InAppBrowser`)
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* iOS
* Windows 8 および 8.1
* ブラウザー
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> JavaScript コードに挿入します、 `InAppBrowser` ウィンドウ
ref.executeScript(details, callback);
* **ref**: への参照を `InAppBrowser` ウィンドウ。*(InAppBrowser)*
* **injectDetails** 詳細を実行するスクリプトのいずれかを指定する、 `file` または `code` キー。*(オブジェクト)*
* **ファイル** スクリプトの URL を注入します。
* **コード**: スクリプトのテキストを挿入します。
* **コールバック**: JavaScript コードを注入した後に実行される関数。
* 挿入されたスクリプトが型の場合 `code` 、スクリプトの戻り値は、1 つのパラメーターでコールバックを実行するのに包まれて、 `Array` 。 マルチライン スクリプトについては、最後のステートメントでは、または評価した最後の式の戻り値です。
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* iOS
* Windows 8 および 8.1
* ブラウザー
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### ブラウザーの癖
* **code**キーのみをサポートします。
### Windows の癖
[MSDN ドキュメント](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx)のため呼び出されたスクリプト パラメーターを返す文字列値のみそれ以外の場合は、**コールバック**に渡される`[null]`になります.
## insertCSS
> CSS に注入する、 `InAppBrowser` ウィンドウ。
ref.insertCSS(details, callback);
* **ref**: への参照を `InAppBrowser` ウィンドウ*(InAppBrowser)*
* **injectDetails** 詳細を実行するスクリプトのいずれかを指定する、 `file` または `code` キー。*(オブジェクト)*
* **ファイル**: 注入するスタイル シートの URL。
* **コード**: 注入するスタイル シートのテキスト。
* **コールバック**: CSS の注入後に実行される関数。
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* iOS
* Windows
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,357 +0,0 @@
<!---
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.
-->
# cordova-plugin-inappbrowser
このプラグインは `コルドバを呼び出すときに表示される web ブラウザーのビューを提供します。InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
`コルドバ。InAppBrowser.open()` `window.open()` 関数との交換を定義する関数。 既存の `window.open()` 呼び出しは、window.open を置き換えることによって InAppBrowser ウィンドウを使用できます。
window.open = cordova.InAppBrowser.open;
InAppBrowser ウィンドウは標準的な web ブラウザーのように動作し、コルドバ Api にアクセスできません。 この理由から、InAppBrowser お勧めする場合はメインのコルドバの webview を読み込むのではなくサード パーティ (信頼されていない) コンテンツをロードする必要があります。 InAppBrowser、ホワイト リストの対象ではないも、システムのブラウザーでリンクを開くです。
InAppBrowser を提供しますデフォルトで GUI コントロール (戻る、進む、行う)。
後方互換性、このプラグインは、また `window.open` をフックのため。 ただし、`window.open` のプラグイン インストール フックを持つことができます意図しない副作用 (特に場合は、このプラグインは別のプラグインの依存関係としてのみ含まれています)。 `window.open` のフックは、将来のメジャー リリースで削除されます。 プラグインから、フックが削除されるまでアプリはデフォルトの動作を手動で復元できます。
delete window.open // Reverts the call back to it's prototype's default
`window.open` はグローバル スコープでは、InAppBrowser は、`deviceready` イベントの後まで利用できません。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## インストール
cordova plugin add cordova-plugin-inappbrowser
InAppBrowser を通過するアプリですべてのページの読み込みをする場合は初期化中に `window.open` を単にフックできます。たとえば。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
新しい `InAppBrowser` インスタンスを現在のブラウザー インスタンスまたはシステムのブラウザーで URL を開きます。
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref**: への参照を `InAppBrowser` ウィンドウ。*(InAppBrowser)*
* **url**: *(文字列)*をロードする URL。電話 `encodeURI()` 場合は、この上の URL は Unicode 文字を含みます。
* **ターゲット**: ターゲット URL は、既定値は、省略可能なパラメーターをロードするを `_self` 。*(文字列)*
* `_self`: コルドバ WebView URL がホワイト リストにある場合で開きます、それ以外の場合で開きます、`InAppBrowser`.
* `_blank`: で開きます、`InAppBrowser`.
* `_system`: システムの web ブラウザーで開きます。
* **オプション**: おぷしょん、 `InAppBrowser` 。省略可能にする: `location=yes` 。*(文字列)*
`options`文字列にはする必要があります任意の空白スペースが含まれていないと、各機能の名前と値のペアをコンマで区切る必要があります。 機能名では大文字小文字を区別します。 以下の値をサポートするプラットフォーム。
* **場所** に設定 `yes` または `no` を有効にする、 `InAppBrowser` の場所バー オンまたはオフにします。
アンドロイドのみ:
* **非表示**: 設定 `yes` ブラウザーを作成して、ページの読み込みが表示されません。 Loadstop イベントは、読み込みが完了すると発生します。 省略するか設定 `no` (既定値) を開くし、通常読み込みブラウザーを持っています。
* **clearcache**: に設定されている `yes` 、ブラウザーのクッキー キャッシュ クリア新しいウィンドウが開く前に
* **clearsessioncache** に設定されている `yes` はセッション cookie のキャッシュをオフにすると、新しいウィンドウが開く前に
iOS のみ:
* **closebuttoncaption**: [**完了**] ボタンのキャプションとして使用する文字列に設定します。自分でこの値をローカライズする必要があることに注意してください。
* **disallowoverscroll** に設定されている `yes` または `no` (既定値は `no` )。/UIWebViewBounce プロパティをオフにします。
* **非表示**: 設定 `yes` ブラウザーを作成して、ページの読み込みが表示されません。 Loadstop イベントは、読み込みが完了すると発生します。 省略するか設定 `no` (既定値) を開くし、通常読み込みブラウザーを持っています。
* **clearcache**: に設定されている `yes` 、ブラウザーのクッキー キャッシュ クリア新しいウィンドウが開く前に
* **clearsessioncache** に設定されている `yes` はセッション cookie のキャッシュをオフにすると、新しいウィンドウが開く前に
* **ツールバー**: に設定されている `yes` または `no` InAppBrowser (デフォルトのツールバーのオンまたはオフを有効にするには`yes`)
* **enableViewportScale** に設定されている `yes` または `no` を (デフォルトではメタタグを介してスケーリング ビューポートを防ぐために`no`).
* **mediaPlaybackRequiresUserAction** に設定されている `yes` または `no` を HTML5 オーディオまたはビデオを自動再生 (初期設定から防ぐために`no`).
* **allowInlineMediaPlayback** に設定されている `yes` または `no` ラインで HTML5 メディア再生には、デバイス固有再生インターフェイスではなく、ブラウザー ウィンドウ内に表示するようにします。 HTML の `video` 要素を含める必要がありますまた、 `webkit-playsinline` 属性 (デフォルトは`no`)
* **keyboardDisplayRequiresUserAction** に設定されている `yes` または `no` をフォーム要素の JavaScript を介してフォーカスを受け取るときに、キーボードを開く `focus()` コール (デフォルトは`yes`).
* **suppressesIncrementalRendering** に設定されている `yes` または `no` (デフォルトでは表示される前にビューのすべての新しいコンテンツを受信するまで待機するには`no`).
* **presentationstyle** に設定されている `pagesheet``formsheet` または `fullscreen` (デフォルトでは、[プレゼンテーション スタイル][1]を設定するには`fullscreen`).
* **transitionstyle** に設定されている `fliphorizontal``crossdissolve` または `coververtical` (デフォルトでは、[トランジションのスタイル][2]を設定するには`coververtical`).
* **toolbarposition** に設定されている `top` または `bottom` (既定値は `bottom` )。上部またはウィンドウの下部にツールバーが発生します。
Windows のみ:
* **非表示**: 設定 `yes` ブラウザーを作成して、ページの読み込みが表示されません。 Loadstop イベントは、読み込みが完了すると発生します。 省略するか設定 `no` (既定値) を開くし、通常読み込みブラウザーを持っています。
[1]: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle
[2]: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* Firefox の OS
* iOS
* Windows 8 および 8.1
* Windows Phone 7 と 8
### 例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS 癖
開かれた場合にいくつかの CSS ルールを追加する必要があるプラグインは任意のデザインを適用しないと `target ='_blank'`。これらのような規則になります。
css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
## InAppBrowser
`コルドバへの呼び出しから返されるオブジェクト。InAppBrowser.open`.
### メソッド
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> イベントのリスナーを追加します、`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ref**: への参照を `InAppBrowser` ウィンドウ*(InAppBrowser)*
* **eventname**: *(文字列)*をリッスンするイベント
* **** イベントが発生するとき、 `InAppBrowser` の URL の読み込みが開始します。
* **loadstop** イベントが発生するとき、 `InAppBrowser` URL の読み込みが完了します。
* **loaderror** イベントが発生するとき、 `InAppBrowser` URL の読み込みでエラーが発生します。
* **終了**: イベントが発生するとき、 `InAppBrowser` ウィンドウが閉じられます。
* **コールバック**: イベントが発生したときに実行される関数。関数に渡されますが、 `InAppBrowserEvent` オブジェクトをパラメーターとして。
### InAppBrowserEvent プロパティ
* **タイプ**: eventname どちらか `loadstart``loadstop``loaderror` 、または `exit` 。*(文字列)*
* **url**: URL が読み込まれました。*(文字列)*
* **コード**: の場合にのみ、エラー コード `loaderror` 。*(数)*
* **メッセージ**: の場合にのみ、エラー メッセージ `loaderror` 。*(文字列)*
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* iOS
* Windows 8 および 8.1
* Windows Phone 7 と 8
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> イベントのリスナーを削除します、`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ref**: への参照を `InAppBrowser` ウィンドウ。*(InAppBrowser)*
* **eventname**: イベントのリッスンを停止します。*(文字列)*
* **** イベントが発生するとき、 `InAppBrowser` の URL の読み込みが開始します。
* **loadstop** イベントが発生するとき、 `InAppBrowser` URL の読み込みが完了します。
* **loaderror** イベントが発生するとき、 `InAppBrowser` URL の読み込みエラーが発生します。
* **終了**: イベントが発生するとき、 `InAppBrowser` ウィンドウが閉じられます。
* **コールバック**: イベントが発生するときに実行する関数。関数に渡されますが、 `InAppBrowserEvent` オブジェクト。
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* iOS
* Windows 8 および 8.1
* Windows Phone 7 と 8
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> 閉じる、 `InAppBrowser` ウィンドウ。
ref.close();
* **ref**: への参照を `InAppBrowser` ウィンドウ*(InAppBrowser)*
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* Firefox の OS
* iOS
* Windows 8 および 8.1
* Windows Phone 7 と 8
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> 隠された開かれた InAppBrowser ウィンドウが表示されます。この関数を呼び出すは影響しません、InAppBrowser が既に表示されている場合。
ref.show();
* **ref**: InAppBrowser ウィンドウ (への参照`InAppBrowser`)
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* iOS
* Windows 8 および 8.1
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> JavaScript コードに挿入します、 `InAppBrowser` ウィンドウ
ref.executeScript(details, callback);
* **ref**: への参照を `InAppBrowser` ウィンドウ。*(InAppBrowser)*
* **injectDetails** 詳細を実行するスクリプトのいずれかを指定する、 `file` または `code` キー。*(オブジェクト)*
* **ファイル** スクリプトの URL を注入します。
* **コード**: スクリプトのテキストを挿入します。
* **コールバック**: JavaScript コードを注入した後に実行される関数。
* 挿入されたスクリプトが型の場合 `code` 、スクリプトの戻り値は、1 つのパラメーターでコールバックを実行するのに包まれて、 `Array` 。 マルチライン スクリプトについては、最後のステートメントでは、または評価した最後の式の戻り値です。
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* iOS
* Windows 8 および 8.1
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
## insertCSS
> CSS に注入する、 `InAppBrowser` ウィンドウ。
ref.insertCSS(details, callback);
* **ref**: への参照を `InAppBrowser` ウィンドウ*(InAppBrowser)*
* **injectDetails** 詳細を実行するスクリプトのいずれかを指定する、 `file` または `code` キー。*(オブジェクト)*
* **ファイル**: 注入するスタイル シートの URL。
* **コード**: 注入するスタイル シートのテキスト。
* **コールバック**: CSS の注入後に実行される関数。
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* iOS
### 簡単な例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,388 +0,0 @@
<!--
# 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.
-->
# cordova-plugin-inappbrowser
[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)
이 플러그인 `코르도바를 호출할 때 표시 하는 웹 브라우저 보기를 제공 합니다.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
`코르도바입니다.InAppBrowser.open()` 함수 `window.open ()` 함수에 대 한 대체품 정의 됩니다. 기존의 `window.open ()` 호출 window.open을 대체 하 여 InAppBrowser 윈도우를 사용할 수 있습니다.
window.open = cordova.InAppBrowser.open;
InAppBrowser 창 표준 웹 브라우저 처럼 동작 및 코르도바 Api에 액세스할 수 없습니다. 이 이유는 InAppBrowser는 것이 좋습니다는 주요 코르도바 webview로 로드 하는 대신 제 3 자 (신뢰할 수 없는) 콘텐츠를 로드 해야 할 경우. InAppBrowser는 허용 될 수도 시스템 브라우저에서 링크를 여는.
사용자에 대 한 자체 GUI 컨트롤에서 기본적으로 제공 된 InAppBrowser (뒤로, 앞으로, 완료).
대 한 뒤 호환성,이 플러그인도 `window.open` 후크. 그러나, `window.open`의 플러그인 설치 후크를 가질 수 있습니다 의도 하지 않은 부작용 (특히 경우이 플러그인이 다른 플러그인 종속성 으로만 포함). `window.open` 후크 주요 릴리스에서 제거 됩니다. 후크 플러그인에서 제거 될 때까지 애플 리 케이 션 수 있습니다 수동으로 기본 동작을 복원 하 게 됩니다.
delete window.open // Reverts the call back to it's prototype's default
`window.open` 전역 범위에 있지만 InAppBrowser 제공 되지 않습니다 때까지 `deviceready` 이벤트 후.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## 설치
cordova plugin add cordova-plugin-inappbrowser
InAppBrowser를 통해가 서 당신의 애플 리 케이 션에서 모든 페이지를 로드 하려는 경우 초기화 하는 동안 `window.open` 간단 하 게 연결할 수 있습니다. 예를 들어:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
`InAppBrowser` 인스턴스, 현재 브라우저 인스턴스 또는 시스템 브라우저에서 URL을 엽니다.
var ref = cordova.InAppBrowser.open(url, target, options);
* **심판**:에 대 한 참조는 `InAppBrowser` 창. *(InAppBrowser)*
* **url**: *(문자열)를*로드 하는 URL. 전화 `encodeURI()` 이 경우에는 URL 유니코드 문자를 포함 합니다.
* **대상**: 대상 URL, 기본적으로 선택적 매개 변수를 로드 하는 `_self` . *(문자열)*
* `_self`: URL 화이트 리스트에 있으면 코르도바 WebView에서 열리고, 그렇지 않으면 열에`InAppBrowser`.
* `_blank`: 준공에`InAppBrowser`.
* `_system`: 시스템의 웹 브라우저에서 엽니다.
* **옵션**: 옵션은 `InAppBrowser` . 선택적, 디폴트에: `location=yes` . *(문자열)*
`options`문자열 텅 빈 어떤 스페이스 포함 해서는 안 그리고 쉼표 각 기능의 이름/값 쌍을 구분 합니다. 기능 이름은 대/소문자입니다. 모든 플랫폼 지원 아래 값:
* **위치**: 설정 `yes` 또는 `no` 설정 하는 `InAppBrowser` 의 위치 표시줄 켜거나 끕니다.
안 드 로이드만:
* **숨겨진**: 설정 `yes` 브라우저를 만들 페이지를 로드 하면, 하지만 그것을 보여주지. Loadstop 이벤트는 로드가 완료 되 면 발생 합니다. 생략 하거나 설정 `no` (기본값) 브라우저 열고 정상적으로 로드 해야 합니다.
* **clearcache**: 설정 `yes` 브라우저를 쿠키 캐시 삭제 하기 전에 새 창이 열립니다
* **clearsessioncache**: 설정 `yes` 세션 쿠키 캐시를 삭제 하기 전에 새 창이 열립니다
* **zoom/축소**: `네` 안 드 로이드 브라우저의 확대/축소 컨트롤을 표시, 그들을 숨길 수 `없는` 로 설정으로 설정. 기본값은 `네`.
* **hardwareback**: 하드웨어 뒤로 버튼을 사용 하 여 `InAppBrowser`의 역사를 통해 뒤로 이동 하려면 `예` 로 설정. 이전 페이지 없음이 있는 경우에, `InAppBrowser` 닫힙니다. 기본 값 이므로 `yes`, 뒤로 버튼을 간단 하 게는 InAppBrowser를 하려면 `no` 로 설정 해야 합니다.
iOS만:
* **closebuttoncaption**: **수행** 하는 단추의 캡션으로 사용할 문자열을 설정 합니다. 참고 직접이 값을 지역화 해야 합니다.
* **disallowoverscroll**: 설정 `yes` 또는 `no` (기본값은 `no` ). 회전 온/오프 UIWebViewBounce 속성입니다.
* **숨겨진**: 설정 `yes` 브라우저를 만들 페이지를 로드 하면, 하지만 그것을 보여주지. Loadstop 이벤트는 로드가 완료 되 면 발생 합니다. 생략 하거나 설정 `no` (기본값) 브라우저 열고 정상적으로 로드 해야 합니다.
* **clearcache**: 설정 `yes` 브라우저를 쿠키 캐시 삭제 하기 전에 새 창이 열립니다
* **clearsessioncache**: 설정 `yes` 세션 쿠키 캐시를 삭제 하기 전에 새 창이 열립니다
* **도구 모음**: 설정 `yes` 또는 `no` InAppBrowser (기본값:에 대 한 도구 모음 온 / 오프를 돌기 위하여`yes`)
* **enableViewportScale**: 설정 `yes` 또는 `no` 뷰포트 메타 태그 (기본값:를 통해 확장을 방지 하기 위해`no`).
* **mediaPlaybackRequiresUserAction**: 설정 `yes` 또는 `no` HTML5 오디오 또는 비디오 자동 재생 (기본값에서에서 방지 하기 위해`no`).
* **allowInlineMediaPlayback**: 설정 `yes` 또는 `no` 인라인 HTML5 미디어 재생, 장치 전용 재생 인터페이스 보다는 브라우저 창 내에서 표시할 수 있도록 합니다. HTML의 `video` 요소가 포함 되어야 합니다는 `webkit-playsinline` 특성 (기본값:`no`)
* **keyboardDisplayRequiresUserAction**: 설정 `yes` 또는 `no` 양식 요소는 자바 스크립트를 통해 포커스를 받을 때 키보드를 열고 `focus()` 전화 (기본값:`yes`).
* **suppressesIncrementalRendering**: 설정 `yes` 또는 `no` (기본값을 렌더링 하기 전에 모든 새로운 보기 콘텐츠를 받을 때까지 기다려야`no`).
* **presentationstyle**: 설정 `pagesheet` , `formsheet` 또는 `fullscreen` [프레 젠 테이 션 스타일](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle) (기본값을 설정 하려면`fullscreen`).
* **transitionstyle**: 설정 `fliphorizontal` , `crossdissolve` 또는 `coververtical` [전환 스타일](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle) (기본값을 설정 하려면`coververtical`).
* **toolbarposition**: 설정 `top` 또는 `bottom` (기본값은 `bottom` ). 위쪽 또는 아래쪽 창에 도구 모음을 발생 합니다.
Windows에만 해당:
* **숨겨진**: 설정 `yes` 브라우저를 만들 페이지를 로드 하면, 하지만 그것을 보여주지. Loadstop 이벤트는 로드가 완료 되 면 발생 합니다. 생략 하거나 설정 `no` (기본값) 브라우저 열고 정상적으로 로드 해야 합니다.
* **fullscreen**: 주위 테두리 없이 브라우저 컨트롤을 만드는 `yes` 를 설정. 참고로 만약 **location=no** 지정, 통제 내 사 창 닫기를 사용자에 게 표시 될 것입니다.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* Firefox 운영 체제
* iOS
* 윈도우 8과 8.1
* Windows Phone 7과 8
* 브라우저
### 예를 들어
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### 파이어 폭스 OS 단점
플러그인 어떤 디자인을 적용 하지 않는 경우 열 일부 CSS의 규칙을 추가할 필요가 있다 `target='_blank'`. 이 같이 규칙
```css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
```
### 윈도우 특수
파이어 폭스 OS 내 사 창 시각적 행동 비슷한 `inAppBrowserWrap`통해 재정의할 수 /`inAppBrowserWrapFullscreen` CSS 클래스
### 브라우저 만지면
* 플러그인은 iframe을 통해 구현
* 탐색 기록 (LocationBar에서`뒤로``앞으로` 단추)은 구현 되지 않습니다.
## InAppBrowser
`Cordova에 대 한 호출에서 반환 하는 개체.InAppBrowser.open`.
### 메서드
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> 이벤트에 대 한 수신기를 추가 합니다`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **심판**:에 대 한 참조는 `InAppBrowser`*(InAppBrowser)*
* **eventname**: *(문자열)를* 수신 하도록 이벤트
* **loadstart**: 이벤트 발생 때는 `InAppBrowser` URL 로드를 시작 합니다.
* **loadstop**: 이벤트가 발생 시기는 `InAppBrowser` URL 로드 완료.
* **loaderror**: 이벤트 발생 때는 `InAppBrowser` URL을 로드할 때 오류가 발생 합니다.
* **종료**: 이벤트가 발생 시기는 `InAppBrowser` 창이 닫힙니다.
* **콜백**: 이벤트가 발생 될 때 실행 되는 함수. 함수는 전달 된 `InAppBrowserEvent` 개체를 매개 변수로 합니다.
### InAppBrowserEvent 속성
* **유형**: eventname, 중 `loadstart` , `loadstop` , `loaderror` , 또는 `exit` . *(문자열)*
* **url**: URL 로드 된. *(문자열)*
* **코드**: 오류 코드의 경우에만 `loaderror` . *(수)*
* **메시지**: 오류 메시지의 경우에만 `loaderror` . *(문자열)*
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* iOS
* 윈도우 8과 8.1
* Windows Phone 7과 8
* 브라우저
### 브라우저 만지면
`loadstart``loaderror` 이벤트 해 고는 되 고.
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> 이벤트에 대 한 수신기를 제거 합니다`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **심판**:에 대 한 참조는 `InAppBrowser` 창. *(InAppBrowser)*
* **eventname**: 이벤트 수신 대기를 중지 합니다. *(문자열)*
* **loadstart**: 이벤트 발생 때는 `InAppBrowser` URL 로드를 시작 합니다.
* **loadstop**: 이벤트가 발생 시기는 `InAppBrowser` URL 로드 완료.
* **loaderror**: 이벤트 발생 때는 `InAppBrowser` URL 로드 오류가 발생 합니다.
* **종료**: 이벤트가 발생 시기는 `InAppBrowser` 창이 닫힙니다.
* **콜백**: 이벤트가 발생 하면 실행할 함수. 함수는 전달 된 `InAppBrowserEvent` 개체.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* iOS
* 윈도우 8과 8.1
* Windows Phone 7과 8
* 브라우저
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> 종료는 `InAppBrowser` 창.
ref.close();
* **심판**:에 대 한 참조는 `InAppBrowser`*(InAppBrowser)*
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* Firefox 운영 체제
* iOS
* 윈도우 8과 8.1
* Windows Phone 7과 8
* 브라우저
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> 숨겨진 열은 한 InAppBrowser 창을 표시 합니다. 전화는 InAppBrowser가 이미 보이는 경우는 효과가 없습니다.
ref.show();
* **ref**: InAppBrowser 창 (참조`InAppBrowser`)
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* iOS
* 윈도우 8과 8.1
* 브라우저
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> 에 자바 스크립트 코드를 삽입는 `InAppBrowser` 창
ref.executeScript(details, callback);
* **심판**:에 대 한 참조는 `InAppBrowser` 창. *(InAppBrowser)*
* **injectDetails**: 스크립트 실행의 세부 사항 중 하나를 지정 하는 `file` 또는 `code` 키. *(개체)*
* **파일**: 삽입 하는 스크립트의 URL.
* **코드**: 스크립트 텍스트를 삽입 합니다.
* **콜백**: 자바 스크립트 코드를 주입 후 실행 기능.
* 삽입 된 스크립트 유형의 경우 `code` , 스크립트의 반환 값은 단일 매개 변수는 콜백 실행에 싸여 있는 `Array` . 여러 줄 스크립트에 대 한 마지막 문 또는 평가 마지막 식의 반환 값입니다.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* iOS
* 윈도우 8과 8.1
* 브라우저
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### 브라우저 만지면
* **code** 키만 지원 됩니다.
### 윈도우 특수
[MSDN 문서](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx) 인해 호출된 스크립트 반환할 수 있습니다 문자열 값만 그렇지 않으면 매개 변수, **콜백** 전달 `[null]` 될 것입니다..
## insertCSS
> 주사로 CSS는 `InAppBrowser` 창.
ref.insertCSS(details, callback);
* **심판**:에 대 한 참조는 `InAppBrowser`*(InAppBrowser)*
* **injectDetails**: 스크립트 실행의 세부 사항 중 하나를 지정 하는 `file` 또는 `code` 키. *(개체)*
* **파일**: 삽입 하는 스타일 시트의 URL.
* **코드**: 삽입 하는 스타일 시트의 텍스트.
* **콜백**: CSS 주입 후 실행 기능.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* iOS
* 윈도우
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,357 +0,0 @@
<!---
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.
-->
# cordova-plugin-inappbrowser
이 플러그인 `코르도바를 호출할 때 표시 하는 웹 브라우저 보기를 제공 합니다.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
`코르도바입니다.InAppBrowser.open()` 함수 `window.open ()` 함수에 대 한 대체품 정의 됩니다. 기존의 `window.open ()` 호출 window.open을 대체 하 여 InAppBrowser 윈도우를 사용할 수 있습니다.
window.open = cordova.InAppBrowser.open;
InAppBrowser 창 표준 웹 브라우저 처럼 동작 및 코르도바 Api에 액세스할 수 없습니다. 이 이유는 InAppBrowser는 것이 좋습니다는 주요 코르도바 webview로 로드 하는 대신 제 3 자 (신뢰할 수 없는) 콘텐츠를 로드 해야 할 경우. InAppBrowser는 허용 될 수도 시스템 브라우저에서 링크를 여는.
사용자에 대 한 자체 GUI 컨트롤에서 기본적으로 제공 된 InAppBrowser (뒤로, 앞으로, 완료).
대 한 뒤 호환성,이 플러그인도 `window.open` 후크. 그러나, `window.open`의 플러그인 설치 후크를 가질 수 있습니다 의도 하지 않은 부작용 (특히 경우이 플러그인이 다른 플러그인 종속성 으로만 포함). `window.open` 후크 주요 릴리스에서 제거 됩니다. 후크 플러그인에서 제거 될 때까지 애플 리 케이 션 수 있습니다 수동으로 기본 동작을 복원 하 게 됩니다.
delete window.open // Reverts the call back to it's prototype's default
`window.open` 전역 범위에 있지만 InAppBrowser 제공 되지 않습니다 때까지 `deviceready` 이벤트 후.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## 설치
cordova plugin add cordova-plugin-inappbrowser
InAppBrowser를 통해가 서 당신의 애플 리 케이 션에서 모든 페이지를 로드 하려는 경우 초기화 하는 동안 `window.open` 간단 하 게 연결할 수 있습니다. 예를 들어:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
`InAppBrowser` 인스턴스, 현재 브라우저 인스턴스 또는 시스템 브라우저에서 URL을 엽니다.
var ref = cordova.InAppBrowser.open(url, target, options);
* **심판**:에 대 한 참조는 `InAppBrowser` 창. *(InAppBrowser)*
* **url**: *(문자열)를*로드 하는 URL. 전화 `encodeURI()` 이 경우에는 URL 유니코드 문자를 포함 합니다.
* **대상**: 대상 URL, 기본적으로 선택적 매개 변수를 로드 하는 `_self` . *(문자열)*
* `_self`: URL 화이트 리스트에 있으면 코르도바 WebView에서 열리고, 그렇지 않으면 열에`InAppBrowser`.
* `_blank`: 준공에`InAppBrowser`.
* `_system`: 시스템의 웹 브라우저에서 엽니다.
* **옵션**: 옵션은 `InAppBrowser` . 선택적, 디폴트에: `location=yes` . *(문자열)*
`options`문자열 텅 빈 어떤 스페이스 포함 해서는 안 그리고 쉼표 각 기능의 이름/값 쌍을 구분 합니다. 기능 이름은 대/소문자입니다. 모든 플랫폼 지원 아래 값:
* **위치**: 설정 `yes` 또는 `no` 설정 하는 `InAppBrowser` 의 위치 표시줄 켜거나 끕니다.
안 드 로이드만:
* **숨겨진**: 설정 `yes` 브라우저를 만들 페이지를 로드 하면, 하지만 그것을 보여주지. Loadstop 이벤트는 로드가 완료 되 면 발생 합니다. 생략 하거나 설정 `no` (기본값) 브라우저 열고 정상적으로 로드 해야 합니다.
* **clearcache**: 설정 `yes` 브라우저를 쿠키 캐시 삭제 하기 전에 새 창이 열립니다
* **clearsessioncache**: 설정 `yes` 세션 쿠키 캐시를 삭제 하기 전에 새 창이 열립니다
iOS만:
* **closebuttoncaption**: **수행** 하는 단추의 캡션으로 사용할 문자열을 설정 합니다. 참고 직접이 값을 지역화 해야 합니다.
* **disallowoverscroll**: 설정 `yes` 또는 `no` (기본값은 `no` ). 회전 온/오프 UIWebViewBounce 속성입니다.
* **숨겨진**: 설정 `yes` 브라우저를 만들 페이지를 로드 하면, 하지만 그것을 보여주지. Loadstop 이벤트는 로드가 완료 되 면 발생 합니다. 생략 하거나 설정 `no` (기본값) 브라우저 열고 정상적으로 로드 해야 합니다.
* **clearcache**: 설정 `yes` 브라우저를 쿠키 캐시 삭제 하기 전에 새 창이 열립니다
* **clearsessioncache**: 설정 `yes` 세션 쿠키 캐시를 삭제 하기 전에 새 창이 열립니다
* **도구 모음**: 설정 `yes` 또는 `no` InAppBrowser (기본값:에 대 한 도구 모음 온 / 오프를 돌기 위하여`yes`)
* **enableViewportScale**: 설정 `yes` 또는 `no` 뷰포트 메타 태그 (기본값:를 통해 확장을 방지 하기 위해`no`).
* **mediaPlaybackRequiresUserAction**: 설정 `yes` 또는 `no` HTML5 오디오 또는 비디오 자동 재생 (기본값에서에서 방지 하기 위해`no`).
* **allowInlineMediaPlayback**: 설정 `yes` 또는 `no` 인라인 HTML5 미디어 재생, 장치 전용 재생 인터페이스 보다는 브라우저 창 내에서 표시할 수 있도록 합니다. HTML의 `video` 요소가 포함 되어야 합니다는 `webkit-playsinline` 특성 (기본값:`no`)
* **keyboardDisplayRequiresUserAction**: 설정 `yes` 또는 `no` 양식 요소는 자바 스크립트를 통해 포커스를 받을 때 키보드를 열고 `focus()` 전화 (기본값:`yes`).
* **suppressesIncrementalRendering**: 설정 `yes` 또는 `no` (기본값을 렌더링 하기 전에 모든 새로운 보기 콘텐츠를 받을 때까지 기다려야`no`).
* **presentationstyle**: 설정 `pagesheet` , `formsheet` 또는 `fullscreen` [프레 젠 테이 션 스타일][1] (기본값을 설정 하려면`fullscreen`).
* **transitionstyle**: 설정 `fliphorizontal` , `crossdissolve` 또는 `coververtical` [전환 스타일][2] (기본값을 설정 하려면`coververtical`).
* **toolbarposition**: 설정 `top` 또는 `bottom` (기본값은 `bottom` ). 위쪽 또는 아래쪽 창에 도구 모음을 발생 합니다.
Windows에만 해당:
* **숨겨진**: 설정 `yes` 브라우저를 만들 페이지를 로드 하면, 하지만 그것을 보여주지. Loadstop 이벤트는 로드가 완료 되 면 발생 합니다. 생략 하거나 설정 `no` (기본값) 브라우저 열고 정상적으로 로드 해야 합니다.
[1]: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle
[2]: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* Firefox 운영 체제
* iOS
* 윈도우 8과 8.1
* Windows Phone 7과 8
### 예를 들어
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### 파이어 폭스 OS 단점
플러그인 어떤 디자인을 적용 하지 않는 경우 열 일부 CSS의 규칙을 추가할 필요가 있다 `target='_blank'`. 이 같이 규칙
css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
## InAppBrowser
`Cordova에 대 한 호출에서 반환 하는 개체.InAppBrowser.open`.
### 메서드
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> 이벤트에 대 한 수신기를 추가 합니다`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **심판**:에 대 한 참조는 `InAppBrowser`*(InAppBrowser)*
* **eventname**: *(문자열)를* 수신 하도록 이벤트
* **loadstart**: 이벤트 발생 때는 `InAppBrowser` URL 로드를 시작 합니다.
* **loadstop**: 이벤트가 발생 시기는 `InAppBrowser` URL 로드 완료.
* **loaderror**: 이벤트 발생 때는 `InAppBrowser` URL을 로드할 때 오류가 발생 합니다.
* **종료**: 이벤트가 발생 시기는 `InAppBrowser` 창이 닫힙니다.
* **콜백**: 이벤트가 발생 될 때 실행 되는 함수. 함수는 전달 된 `InAppBrowserEvent` 개체를 매개 변수로 합니다.
### InAppBrowserEvent 속성
* **유형**: eventname, 중 `loadstart` , `loadstop` , `loaderror` , 또는 `exit` . *(문자열)*
* **url**: URL 로드 된. *(문자열)*
* **코드**: 오류 코드의 경우에만 `loaderror` . *(수)*
* **메시지**: 오류 메시지의 경우에만 `loaderror` . *(문자열)*
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* iOS
* 윈도우 8과 8.1
* Windows Phone 7과 8
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> 이벤트에 대 한 수신기를 제거 합니다`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **심판**:에 대 한 참조는 `InAppBrowser` 창. *(InAppBrowser)*
* **eventname**: 이벤트 수신 대기를 중지 합니다. *(문자열)*
* **loadstart**: 이벤트 발생 때는 `InAppBrowser` URL 로드를 시작 합니다.
* **loadstop**: 이벤트가 발생 시기는 `InAppBrowser` URL 로드 완료.
* **loaderror**: 이벤트 발생 때는 `InAppBrowser` URL 로드 오류가 발생 합니다.
* **종료**: 이벤트가 발생 시기는 `InAppBrowser` 창이 닫힙니다.
* **콜백**: 이벤트가 발생 하면 실행할 함수. 함수는 전달 된 `InAppBrowserEvent` 개체.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* iOS
* 윈도우 8과 8.1
* Windows Phone 7과 8
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> 종료는 `InAppBrowser` 창.
ref.close();
* **심판**:에 대 한 참조는 `InAppBrowser`*(InAppBrowser)*
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* Firefox 운영 체제
* iOS
* 윈도우 8과 8.1
* Windows Phone 7과 8
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> 숨겨진 열은 한 InAppBrowser 창을 표시 합니다. 전화는 InAppBrowser가 이미 보이는 경우는 효과가 없습니다.
ref.show();
* **ref**: InAppBrowser 창 (참조`InAppBrowser`)
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* iOS
* 윈도우 8과 8.1
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> 에 자바 스크립트 코드를 삽입는 `InAppBrowser` 창
ref.executeScript(details, callback);
* **심판**:에 대 한 참조는 `InAppBrowser` 창. *(InAppBrowser)*
* **injectDetails**: 스크립트 실행의 세부 사항 중 하나를 지정 하는 `file` 또는 `code` 키. *(개체)*
* **파일**: 삽입 하는 스크립트의 URL.
* **코드**: 스크립트 텍스트를 삽입 합니다.
* **콜백**: 자바 스크립트 코드를 주입 후 실행 기능.
* 삽입 된 스크립트 유형의 경우 `code` , 스크립트의 반환 값은 단일 매개 변수는 콜백 실행에 싸여 있는 `Array` . 여러 줄 스크립트에 대 한 마지막 문 또는 평가 마지막 식의 반환 값입니다.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* iOS
* 윈도우 8과 8.1
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
## insertCSS
> 주사로 CSS는 `InAppBrowser` 창.
ref.insertCSS(details, callback);
* **심판**:에 대 한 참조는 `InAppBrowser`*(InAppBrowser)*
* **injectDetails**: 스크립트 실행의 세부 사항 중 하나를 지정 하는 `file` 또는 `code` 키. *(개체)*
* **파일**: 삽입 하는 스타일 시트의 URL.
* **코드**: 삽입 하는 스타일 시트의 텍스트.
* **콜백**: CSS 주입 후 실행 기능.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* iOS
### 빠른 예제
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,388 +0,0 @@
<!--
# 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.
-->
# cordova-plugin-inappbrowser
[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)
Plugin daje widok przeglądarki sieci web, które są wyświetlane podczas wywoływania `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
`cordova.InAppBrowser.open()` funkcja jest definiowana jako zamiennik dla funkcji `window.open()`. Istniejące wywołania `window.open()` służy okno InAppBrowser, zastępując window.open:
window.open = cordova.InAppBrowser.open;
Okna InAppBrowser zachowuje się jak standardowe przeglądarki i nie ma dostępu do API Cordova. Z tego powodu zaleca się InAppBrowser jeśli ty potrzebować wobec ciężar (niezaufanej) treści osób trzecich, a nie że wczytywanie głównym webview Cordova. InAppBrowser nie jest biała, ani nie jest otwieranie linków w przeglądarce systemu.
InAppBrowser zawiera domyślnie kontrole GUI dla użytkownika (tył, przód, zrobić).
Do tyłu zgodności, ten plugin również haki `window.open`. Jednak może mieć zainstalowane wtyczki haka `window.open` niezamierzone skutki uboczne (zwłaszcza, jeśli ten plugin jest włączone tylko jako część innej wtyczki). Hak `window.open` zostaną usunięte w przyszłej wersji głównych. Dopóki hak jest usuwany z wtyczki, aplikacje można ręcznie przywrócić domyślne zachowanie:
delete window.open // Reverts the call back to it's prototype's default
Chociaż `window.open` w globalnym zasięgu, InAppBrowser nie jest dostępne dopiero po zdarzeniu `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Instalacja
cordova plugin add cordova-plugin-inappbrowser
Jeśli chcesz wszystko stronica ładunki w swojej aplikacji, aby przejść przez InAppBrowser, można po prostu podłączyć `window.open` podczas inicjowania. Na przykład:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Otwiera URL w nowe wystąpienie `InAppBrowser`, bieżące wystąpienie przeglądarki lub przeglądarki systemu.
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref**: odniesienie do `InAppBrowser` okna. *(InAppBrowser)*
* **adres**: adres URL do ładowania *(ciąg)*. Wywołanie `encodeURI()` na to, czy adres URL zawiera znaki Unicode.
* **miejsce docelowe**: miejsce docelowe, w którym wobec ciężar ten URL parametr opcjonalny, który domyślnie `_self` . *(String)*
* `_self`: Otwiera w Cordova WebView, jeśli adres URL jest na białej liście, inaczej ono otwiera w`InAppBrowser`.
* `_blank`: Otwiera w`InAppBrowser`.
* `_system`: Otwiera w przeglądarce internetowej systemu.
* **Opcje**: opcje dla `InAppBrowser` . Opcjonalnie, nie stawiła się: `location=yes` . *(String)*
`options`Ciąg nie może zawierać żadnych spacji, i pary nazwa/wartość każdej funkcji muszą być oddzielone przecinkami. Nazwy funkcji jest rozróżniana. Wszystkich platform obsługuje wartości poniżej:
* **Lokalizacja**: zestaw `yes` lub `no` Aby włączyć `InAppBrowser` na pasek lub wyłączyć.
Android:
* **ukryte**: zestaw `yes` do stworzenia przeglądarki i ładowania strony, ale nie pokazuje go. Loadstop zdarzenie fires po zakończeniu ładowania. Pominąć lub zestaw `no` (domyślnie) do przeglądarki otworzyć i załadować normalnie.
* **ClearCache**: zestaw `yes` do przeglądarki w pamięci podręcznej plików cookie wyczyszczone zanim otworzy się nowe okno
* **clearsessioncache**: zestaw `yes` mieć w pamięci podręcznej plików cookie sesji wyczyszczone zanim otworzy się nowe okno
* **zoom**: `yes` aby pokazać formantami powiększania Android przeglądarka, ustawiona na `nie` aby je ukryć. Wartość domyślna to `tak`.
* **hardwareback**: zestaw do `yes` , aby użyć przycisk Wstecz sprzętu do nawigacji wstecz historii `InAppBrowser`. Jeśli nie ma żadnej poprzedniej strony, `InAppBrowser` zostanie zamknięta. Wartością domyślną jest `yes`, więc należy ustawić ją na `no` jeśli chcesz przycisk Wstecz, aby po prostu zamknąć InAppBrowser.
tylko iOS:
* **closebuttoncaption**: aby użyć jak **zrobić** przycisk Podpis ustawiona na ciąg. Należy pamiętać, że trzeba zlokalizować tę wartość siebie.
* **disallowoverscroll**: zestaw `yes` lub `no` (domyślnie `no` ). Włącza/wyłącza właściwość UIWebViewBounce.
* **ukryte**: zestaw `yes` do stworzenia przeglądarki i ładowania strony, ale nie pokazuje go. Loadstop zdarzenie fires po zakończeniu ładowania. Pominąć lub zestaw `no` (domyślnie) do przeglądarki otworzyć i załadować normalnie.
* **ClearCache**: zestaw `yes` do przeglądarki w pamięci podręcznej plików cookie wyczyszczone zanim otworzy się nowe okno
* **clearsessioncache**: zestaw `yes` mieć w pamięci podręcznej plików cookie sesji wyczyszczone zanim otworzy się nowe okno
* **pasek narzędzi**: zestaw `yes` lub `no` Aby włączyć pasek narzędzi lub wyłączyć dla InAppBrowser (domyślnie`yes`)
* **enableViewportScale**: zestaw `yes` lub `no` Aby zapobiec rzutni skalowanie za pomocą tagu meta (domyślnie`no`).
* **mediaPlaybackRequiresUserAction**: zestaw `yes` lub `no` Aby zapobiec HTML5 audio lub wideo z Autoodtwarzanie (domyślnie`no`).
* **allowInlineMediaPlayback**: zestaw `yes` lub `no` Aby w linii HTML5 odtwarzanie, wyświetlanie w oknie przeglądarki, a nie interfejs odtwarzanie specyficzne dla urządzenia. HTML `video` również musi zawierać element `webkit-playsinline` atrybut (domyślnie`no`)
* **keyboardDisplayRequiresUserAction**: zestaw `yes` lub `no` Aby otworzyć klawiaturę ekranową, gdy elementy formularza ostrości za pomocą JavaScript `focus()` połączenia (domyślnie`yes`).
* **suppressesIncrementalRendering**: zestaw `yes` lub `no` czekać, aż wszystkie nowe widok zawartości jest otrzymane przed renderowany (domyślnie`no`).
* **presentationstyle**: zestaw `pagesheet` , `formsheet` lub `fullscreen` Aby ustawić [styl prezentacji](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle) (domyślnie`fullscreen`).
* **transitionstyle**: zestaw `fliphorizontal` , `crossdissolve` lub `coververtical` Aby ustawić [styl przejścia](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle) (domyślnie`coververtical`).
* **toolbarposition**: zestaw `top` lub `bottom` (domyślnie `bottom` ). Powoduje, że pasek ma być na górze lub na dole okna.
Windows tylko:
* **ukryte**: zestaw `yes` do stworzenia przeglądarki i ładowania strony, ale nie pokazuje go. Loadstop zdarzenie fires po zakończeniu ładowania. Pominąć lub zestaw `no` (domyślnie) do przeglądarki otworzyć i załadować normalnie.
* **fullscreen**: zestaw do `yes` , aby utworzyć formant przeglądarki bez obramowania wokół niego. Należy pamiętać, że jeśli **location=no** również jest określony, nie będzie żadnej kontroli przedstawione do użytkownika, aby zamknąć okno IAB.
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 i 8.1
* Windows Phone 7 i 8
* Przeglądarka
### Przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS dziwactwa
Jak plugin nie wymuszać każdy projekt to trzeba dodać pewne reguły CSS jeśli otwarty z `target = "_blank"`. Zasady może wyglądać jak te
```css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
```
### Windows dziwactwa
Podobne do Firefox OS IAB okno wizualne zachowanie może być zastąpiona przez `inAppBrowserWrap`/`inAppBrowserWrapFullscreen` klas CSS
### Quirks przeglądarki
* Plugin jest realizowane za pośrednictwem iframe,
* Historia nawigacji (przyciski`wstecz` i `do przodu` w LocationBar) nie jest zaimplementowana.
## InAppBrowser
Obiekt zwrócony z wywołania `cordova.InAppBrowser.open`.
### Metody
* metody addEventListener
* removeEventListener
* Zamknij
* Pokaż
* executeScript
* insertCSS
## metody addEventListener
> Dodaje detektor zdarzenia z`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ref**: odniesienie do `InAppBrowser` okna *(InAppBrowser)*
* **EventName**: zdarzenie słuchać *(String)*
* **loadstart**: zdarzenie gdy odpalam `InAppBrowser` zaczyna się ładować adresu URL.
* **loadstop**: zdarzenie gdy odpalam `InAppBrowser` zakończeniu ładowania adresu URL.
* **LoadError**: zdarzenie odpala gdy `InAppBrowser` napotka błąd podczas ładowania adresu URL.
* **wyjście**: zdarzenie gdy odpalam `InAppBrowser` okno jest zamknięte.
* **wywołania zwrotnego**: funkcja, która wykonuje, gdy zdarzenie. Funkcja jest przekazywany `InAppBrowserEvent` obiektu jako parametr.
### Właściwości InAppBrowserEvent
* **Typ**: eventname, albo `loadstart` , `loadstop` , `loaderror` , lub `exit` . *(String)*
* **adres**: adres URL, który został załadowany. *(String)*
* **Kod**: kod błędu, tylko w przypadku `loaderror` . *(Liczba)*
* **wiadomość**: komunikat o błędzie, tylko w przypadku `loaderror` . *(String)*
### Obsługiwane platformy
* Amazon Fire OS
* Android
* iOS
* Windows 8 i 8.1
* Windows Phone 7 i 8
* Przeglądarka
### Quirks przeglądarki
wydarzenia `loadstart` i `loaderror` nie są być opalane.
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Usuwa detektor zdarzenia z`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ref**: odniesienie do `InAppBrowser` okna. *(InAppBrowser)*
* **EventName**: zdarzenie przestanie słuchać. *(String)*
* **loadstart**: zdarzenie gdy odpalam `InAppBrowser` zaczyna się ładować adresu URL.
* **loadstop**: zdarzenie gdy odpalam `InAppBrowser` zakończeniu ładowania adresu URL.
* **LoadError**: zdarzenie odpala gdy `InAppBrowser` napotka błąd ładowania adresu URL.
* **wyjście**: zdarzenie gdy odpalam `InAppBrowser` okno jest zamknięte.
* **wywołania zwrotnego**: funkcja do wykonania, gdy zdarzenie. Funkcja jest przekazywany `InAppBrowserEvent` obiektu.
### Obsługiwane platformy
* Amazon Fire OS
* Android
* iOS
* Windows 8 i 8.1
* Windows Phone 7 i 8
* Przeglądarka
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## Zamknij
> Zamyka `InAppBrowser` okna.
ref.close();
* **ref**: odniesienie do `InAppBrowser` okna *(InAppBrowser)*
### Obsługiwane platformy
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows 8 i 8.1
* Windows Phone 7 i 8
* Przeglądarka
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## Pokaż
> Wyświetla InAppBrowser okno, który został otwarty ukryte. Zawód ten jest ignorowany, jeśli InAppBrowser już był widoczny.
ref.show();
* **ref**: odwołanie do InAppBrowser (okno`InAppBrowser`)
### Obsługiwane platformy
* Amazon Fire OS
* Android
* iOS
* Windows 8 i 8.1
* Przeglądarka
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Wstrzykuje kod JavaScript w `InAppBrowser` okna
ref.executeScript(details, callback);
* **ref**: odniesienie do `InAppBrowser` okna. *(InAppBrowser)*
* **injectDetails**: Szczegóły dotyczące skryptu, określając albo `file` lub `code` klucz. *(Obiekt)*
* **plik**: adres URL skryptu, aby wstrzyknąć.
* **Kod**: tekst skryptu, aby wstrzyknąć.
* **wywołania zwrotnego**: funkcja, która wykonuje po kod JavaScript jest wstrzykiwany.
* Jeśli taki skrypt jest typu `code` , wykonuje wywołanie zwrotne z pojedynczym parametrem, który jest wartość zwracana przez skrypt, owinięte w `Array` . Dla wielu linii skrypty to wartość zwracana ostatniej instrukcja, lub ostatni wyrażenie oceniane.
### Obsługiwane platformy
* Amazon Fire OS
* Android
* iOS
* Windows 8 i 8.1
* Przeglądarka
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### Quirks przeglądarki
* obsługiwany jest tylko **code** klucza.
### Windows dziwactwa
Ze względu na [MSDN dokumenty](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx) wywołany skrypt może zwracać tylko wartości ciągów, inaczej parametr, przekazywany do **wywołania zwrotnego** będzie `[null]`.
## insertCSS
> Wstrzykuje CSS w `InAppBrowser` okna.
ref.insertCSS(details, callback);
* **ref**: odniesienie do `InAppBrowser` okna *(InAppBrowser)*
* **injectDetails**: Szczegóły dotyczące skryptu, określając albo `file` lub `code` klucz. *(Obiekt)*
* **plik**: URL arkusza stylów do wsuwania.
* **Kod**: tekst z arkusza stylów do wstrzykiwania.
* **wywołania zwrotnego**: funkcja, która wykonuje po CSS jest wstrzykiwany.
### Obsługiwane platformy
* Amazon Fire OS
* Android
* iOS
* Windows
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,357 +0,0 @@
<!---
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.
-->
# cordova-plugin-inappbrowser
Plugin daje widok przeglądarki sieci web, które są wyświetlane podczas wywoływania `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
`cordova.InAppBrowser.open()` funkcja jest definiowana jako zamiennik dla funkcji `window.open()`. Istniejące wywołania `window.open()` służy okno InAppBrowser, zastępując window.open:
window.open = cordova.InAppBrowser.open;
Okna InAppBrowser zachowuje się jak standardowe przeglądarki i nie ma dostępu do API Cordova. Z tego powodu zaleca się InAppBrowser jeśli ty potrzebować wobec ciężar (niezaufanej) treści osób trzecich, a nie że wczytywanie głównym webview Cordova. InAppBrowser nie jest biała, ani nie jest otwieranie linków w przeglądarce systemu.
InAppBrowser zawiera domyślnie kontrole GUI dla użytkownika (tył, przód, zrobić).
Do tyłu zgodności, ten plugin również haki `window.open`. Jednak może mieć zainstalowane wtyczki haka `window.open` niezamierzone skutki uboczne (zwłaszcza, jeśli ten plugin jest włączone tylko jako część innej wtyczki). Hak `window.open` zostaną usunięte w przyszłej wersji głównych. Dopóki hak jest usuwany z wtyczki, aplikacje można ręcznie przywrócić domyślne zachowanie:
delete window.open // Reverts the call back to it's prototype's default
Chociaż `window.open` w globalnym zasięgu, InAppBrowser nie jest dostępne dopiero po zdarzeniu `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Instalacja
cordova plugin add cordova-plugin-inappbrowser
Jeśli chcesz wszystko stronica ładunki w swojej aplikacji, aby przejść przez InAppBrowser, można po prostu podłączyć `window.open` podczas inicjowania. Na przykład:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Otwiera URL w nowe wystąpienie `InAppBrowser`, bieżące wystąpienie przeglądarki lub przeglądarki systemu.
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref**: odniesienie do `InAppBrowser` okna. *(InAppBrowser)*
* **adres**: adres URL do ładowania *(ciąg)*. Wywołanie `encodeURI()` na to, czy adres URL zawiera znaki Unicode.
* **miejsce docelowe**: miejsce docelowe, w którym wobec ciężar ten URL parametr opcjonalny, który domyślnie `_self` . *(String)*
* `_self`: Otwiera w Cordova WebView, jeśli adres URL jest na białej liście, inaczej ono otwiera w`InAppBrowser`.
* `_blank`: Otwiera w`InAppBrowser`.
* `_system`: Otwiera w przeglądarce internetowej systemu.
* **Opcje**: opcje dla `InAppBrowser` . Opcjonalnie, nie stawiła się: `location=yes` . *(String)*
`options`Ciąg nie może zawierać żadnych spacji, i pary nazwa/wartość każdej funkcji muszą być oddzielone przecinkami. Nazwy funkcji jest rozróżniana. Wszystkich platform obsługuje wartości poniżej:
* **Lokalizacja**: zestaw `yes` lub `no` Aby włączyć `InAppBrowser` na pasek lub wyłączyć.
Android:
* **ukryte**: zestaw `yes` do stworzenia przeglądarki i ładowania strony, ale nie pokazuje go. Loadstop zdarzenie fires po zakończeniu ładowania. Pominąć lub zestaw `no` (domyślnie) do przeglądarki otworzyć i załadować normalnie.
* **ClearCache**: zestaw `yes` do przeglądarki w pamięci podręcznej plików cookie wyczyszczone zanim otworzy się nowe okno
* **clearsessioncache**: zestaw `yes` mieć w pamięci podręcznej plików cookie sesji wyczyszczone zanim otworzy się nowe okno
tylko iOS:
* **closebuttoncaption**: aby użyć jak **zrobić** przycisk Podpis ustawiona na ciąg. Należy pamiętać, że trzeba zlokalizować tę wartość siebie.
* **disallowoverscroll**: zestaw `yes` lub `no` (domyślnie `no` ). Włącza/wyłącza właściwość UIWebViewBounce.
* **ukryte**: zestaw `yes` do stworzenia przeglądarki i ładowania strony, ale nie pokazuje go. Loadstop zdarzenie fires po zakończeniu ładowania. Pominąć lub zestaw `no` (domyślnie) do przeglądarki otworzyć i załadować normalnie.
* **ClearCache**: zestaw `yes` do przeglądarki w pamięci podręcznej plików cookie wyczyszczone zanim otworzy się nowe okno
* **clearsessioncache**: zestaw `yes` mieć w pamięci podręcznej plików cookie sesji wyczyszczone zanim otworzy się nowe okno
* **pasek narzędzi**: zestaw `yes` lub `no` Aby włączyć pasek narzędzi lub wyłączyć dla InAppBrowser (domyślnie`yes`)
* **enableViewportScale**: zestaw `yes` lub `no` Aby zapobiec rzutni skalowanie za pomocą tagu meta (domyślnie`no`).
* **mediaPlaybackRequiresUserAction**: zestaw `yes` lub `no` Aby zapobiec HTML5 audio lub wideo z Autoodtwarzanie (domyślnie`no`).
* **allowInlineMediaPlayback**: zestaw `yes` lub `no` Aby w linii HTML5 odtwarzanie, wyświetlanie w oknie przeglądarki, a nie interfejs odtwarzanie specyficzne dla urządzenia. HTML `video` również musi zawierać element `webkit-playsinline` atrybut (domyślnie`no`)
* **keyboardDisplayRequiresUserAction**: zestaw `yes` lub `no` Aby otworzyć klawiaturę ekranową, gdy elementy formularza ostrości za pomocą JavaScript `focus()` połączenia (domyślnie`yes`).
* **suppressesIncrementalRendering**: zestaw `yes` lub `no` czekać, aż wszystkie nowe widok zawartości jest otrzymane przed renderowany (domyślnie`no`).
* **presentationstyle**: zestaw `pagesheet` , `formsheet` lub `fullscreen` Aby ustawić [styl prezentacji][1] (domyślnie`fullscreen`).
* **transitionstyle**: zestaw `fliphorizontal` , `crossdissolve` lub `coververtical` Aby ustawić [styl przejścia][2] (domyślnie`coververtical`).
* **toolbarposition**: zestaw `top` lub `bottom` (domyślnie `bottom` ). Powoduje, że pasek ma być na górze lub na dole okna.
Windows tylko:
* **ukryte**: zestaw `yes` do stworzenia przeglądarki i ładowania strony, ale nie pokazuje go. Loadstop zdarzenie fires po zakończeniu ładowania. Pominąć lub zestaw `no` (domyślnie) do przeglądarki otworzyć i załadować normalnie.
[1]: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle
[2]: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 i 8.1
* Windows Phone 7 i 8
### Przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS dziwactwa
Jak plugin nie wymuszać każdy projekt to trzeba dodać pewne reguły CSS jeśli otwarty z `target = "_blank"`. Zasady może wyglądać jak te
css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
## InAppBrowser
Obiekt zwrócony z wywołania `cordova.InAppBrowser.open`.
### Metody
* metody addEventListener
* removeEventListener
* Zamknij
* Pokaż
* executeScript
* insertCSS
## metody addEventListener
> Dodaje detektor zdarzenia z`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ref**: odniesienie do `InAppBrowser` okna *(InAppBrowser)*
* **EventName**: zdarzenie słuchać *(String)*
* **loadstart**: zdarzenie gdy odpalam `InAppBrowser` zaczyna się ładować adresu URL.
* **loadstop**: zdarzenie gdy odpalam `InAppBrowser` zakończeniu ładowania adresu URL.
* **LoadError**: zdarzenie odpala gdy `InAppBrowser` napotka błąd podczas ładowania adresu URL.
* **wyjście**: zdarzenie gdy odpalam `InAppBrowser` okno jest zamknięte.
* **wywołania zwrotnego**: funkcja, która wykonuje, gdy zdarzenie. Funkcja jest przekazywany `InAppBrowserEvent` obiektu jako parametr.
### Właściwości InAppBrowserEvent
* **Typ**: eventname, albo `loadstart` , `loadstop` , `loaderror` , lub `exit` . *(String)*
* **adres**: adres URL, który został załadowany. *(String)*
* **Kod**: kod błędu, tylko w przypadku `loaderror` . *(Liczba)*
* **wiadomość**: komunikat o błędzie, tylko w przypadku `loaderror` . *(String)*
### Obsługiwane platformy
* Amazon Fire OS
* Android
* iOS
* Windows 8 i 8.1
* Windows Phone 7 i 8
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Usuwa detektor zdarzenia z`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ref**: odniesienie do `InAppBrowser` okna. *(InAppBrowser)*
* **EventName**: zdarzenie przestanie słuchać. *(String)*
* **loadstart**: zdarzenie gdy odpalam `InAppBrowser` zaczyna się ładować adresu URL.
* **loadstop**: zdarzenie gdy odpalam `InAppBrowser` zakończeniu ładowania adresu URL.
* **LoadError**: zdarzenie odpala gdy `InAppBrowser` napotka błąd ładowania adresu URL.
* **wyjście**: zdarzenie gdy odpalam `InAppBrowser` okno jest zamknięte.
* **wywołania zwrotnego**: funkcja do wykonania, gdy zdarzenie. Funkcja jest przekazywany `InAppBrowserEvent` obiektu.
### Obsługiwane platformy
* Amazon Fire OS
* Android
* iOS
* Windows 8 i 8.1
* Windows Phone 7 i 8
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## Zamknij
> Zamyka `InAppBrowser` okna.
ref.close();
* **ref**: odniesienie do `InAppBrowser` okna *(InAppBrowser)*
### Obsługiwane platformy
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows 8 i 8.1
* Windows Phone 7 i 8
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## Pokaż
> Wyświetla InAppBrowser okno, który został otwarty ukryte. Zawód ten jest ignorowany, jeśli InAppBrowser już był widoczny.
ref.show();
* **ref**: odwołanie do InAppBrowser (okno`InAppBrowser`)
### Obsługiwane platformy
* Amazon Fire OS
* Android
* iOS
* Windows 8 i 8.1
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Wstrzykuje kod JavaScript w `InAppBrowser` okna
ref.executeScript(details, callback);
* **ref**: odniesienie do `InAppBrowser` okna. *(InAppBrowser)*
* **injectDetails**: Szczegóły dotyczące skryptu, określając albo `file` lub `code` klucz. *(Obiekt)*
* **plik**: adres URL skryptu, aby wstrzyknąć.
* **Kod**: tekst skryptu, aby wstrzyknąć.
* **wywołania zwrotnego**: funkcja, która wykonuje po kod JavaScript jest wstrzykiwany.
* Jeśli taki skrypt jest typu `code` , wykonuje wywołanie zwrotne z pojedynczym parametrem, który jest wartość zwracana przez skrypt, owinięte w `Array` . Dla wielu linii skrypty to wartość zwracana ostatniej instrukcja, lub ostatni wyrażenie oceniane.
### Obsługiwane platformy
* Amazon Fire OS
* Android
* iOS
* Windows 8 i 8.1
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
## insertCSS
> Wstrzykuje CSS w `InAppBrowser` okna.
ref.insertCSS(details, callback);
* **ref**: odniesienie do `InAppBrowser` okna *(InAppBrowser)*
* **injectDetails**: Szczegóły dotyczące skryptu, określając albo `file` lub `code` klucz. *(Obiekt)*
* **plik**: URL arkusza stylów do wsuwania.
* **Kod**: tekst z arkusza stylów do wstrzykiwania.
* **wywołania zwrotnego**: funkcja, która wykonuje po CSS jest wstrzykiwany.
### Obsługiwane platformy
* Amazon Fire OS
* Android
* iOS
### Szybki przykład
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,330 +0,0 @@
<!---
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.
-->
# cordova-plugin-inappbrowser
Этот плагин обеспечивает представление веб-браузера, что показывает при вызове`window.open()`.
var ref = window.open('http://apache.org', '_blank', 'location=yes');
**Примечание**: InAppBrowser окно ведет себя как стандартный веб-браузер и не может доступ API Cordova.
## Установка
cordova plugin add cordova-plugin-inappbrowser
## window.open
Открывает URL-адрес в новом `InAppBrowser` например, текущий экземпляр браузера или браузера системы.
var ref = window.open(url, target, options);
* **ссылка**: ссылка для `InAppBrowser` окно. *(InAppBrowser)*
* **URL**: URL-адрес для загрузки *(String)*. Вызвать `encodeURI()` на это, если URL-адрес содержит символы Unicode.
* **Цель**: цель для загрузки URL-адреса, необязательный параметр, по умолчанию `_self` . *(Строка)*
* `_self`: Открывается в Cordova WebView, если URL-адрес в белый список, в противном случае он открывается в`InAppBrowser`.
* `_blank`: Открывает в`InAppBrowser`.
* `_system`: Открывается в веб-браузера системы.
* **опции**: параметры для `InAppBrowser` . Необязательный параметр, виновная в: `location=yes` . *(Строка)*
`options`Строка не должна содержать каких-либо пустое пространство, и каждая функция пар имя/значение должны быть разделены запятой. Функция имена нечувствительны к регистру. Все платформы поддерживают исходное значение:
* **Расположение**: равным `yes` или `no` превратить `InAppBrowser` в адресную строку или выключить.
Только андроид:
* **closebuttoncaption**: задайте строку для использования в качестве заголовка кнопки **сделали** .
* **скрытые**: значение `yes` для создания браузера и загрузки страницы, но не показать его. Событие loadstop возникает, когда загрузка завершена. Опустить или набор `no` (по умолчанию), чтобы браузер открыть и загрузить нормально.
* **ClearCache**: набор `yes` иметь браузера куки кэш очищен перед открытием нового окна
* **clearsessioncache**: значение `yes` иметь кэш cookie сеанса очищается перед открытием нового окна
только iOS:
* **closebuttoncaption**: задайте строку для использования в качестве заголовка кнопки **сделали** . Обратите внимание, что вам нужно самостоятельно локализовать это значение.
* **disallowoverscroll**: значение `yes` или `no` (по умолчанию `no` ). Включает/отключает свойство UIWebViewBounce.
* **скрытые**: значение `yes` для создания браузера и загрузки страницы, но не показать его. Событие loadstop возникает, когда загрузка завершена. Опустить или набор `no` (по умолчанию), чтобы браузер открыть и загрузить нормально.
* **ClearCache**: набор `yes` иметь браузера куки кэш очищен перед открытием нового окна
* **clearsessioncache**: значение `yes` иметь кэш cookie сеанса очищается перед открытием нового окна
* **панели инструментов**: набор `yes` или `no` для включения панели инструментов или выключить InAppBrowser (по умолчанию`yes`)
* **enableViewportScale**: значение `yes` или `no` для предотвращения просмотра, масштабирования через тег meta (по умолчанию`no`).
* **mediaPlaybackRequiresUserAction**: значение `yes` или `no` для предотвращения HTML5 аудио или видео от Автовоспроизведение (по умолчанию`no`).
* **allowInlineMediaPlayback**: значение `yes` или `no` чтобы разрешить воспроизведение мультимедиа HTML5 в строки, отображения в окне браузера, а не конкретного устройства воспроизведения интерфейс. HTML `video` элемент должен также включать `webkit-playsinline` атрибут (по умолчанию`no`)
* **keyboardDisplayRequiresUserAction**: значение `yes` или `no` чтобы открыть клавиатуру, когда формы элементы получают фокус через JavaScript в `focus()` вызов (по умолчанию`yes`).
* **suppressesIncrementalRendering**: значение `yes` или `no` ждать, пока все новое содержание представление получено до визуализации (по умолчанию`no`).
* **presentationstyle**: набор `pagesheet` , `formsheet` или `fullscreen` чтобы задать [стиль презентации][1] (по умолчанию`fullscreen`).
* **transitionstyle**: набор `fliphorizontal` , `crossdissolve` или `coververtical` чтобы задать [стиль перехода][2] (по умолчанию`coververtical`).
* **toolbarposition**: значение `top` или `bottom` (по умолчанию `bottom` ). Вызывает панели инструментов, чтобы быть в верхней или нижней части окна.
Windows только:
* **скрытые**: значение `yes` для создания браузера и загрузки страницы, но не показать его. Событие loadstop возникает, когда загрузка завершена. Опустить или набор `no` (по умолчанию), чтобы браузер открыть и загрузить нормально.
[1]: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle
[2]: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows 8 и 8.1
* Windows Phone 7 и 8
### Пример
var ref = window.open('http://apache.org', '_blank', 'location=yes');
var ref2 = window.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Особенности Firefox OS
Как плагин не применять любой дизайн есть необходимость добавить некоторые правила CSS, если открыт с `target='_blank'` . Правила может выглядеть как эти
css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
## Внутренний браузер
Объект, возвращаемый из вызова`window.open`.
### Методы
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> Добавляет прослушиватель для события от`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ссылка**: ссылка для `InAppBrowser` окно *(InAppBrowser)*
* **EventName**: событие для прослушивания *(String)*
* **loadstart**: событие возникает, когда `InAppBrowser` начинает для загрузки URL-адреса.
* **loadstop**: событие возникает, когда `InAppBrowser` завершит загрузку URL-адреса.
* **loaderror**: событие возникает, когда `InAppBrowser` обнаруживает ошибку при загрузке URL-адреса.
* **выход**: возникает событие, когда `InAppBrowser` окно закрыто.
* **обратного вызова**: функция, которая выполняется, когда возникает событие. Функция передается `InAppBrowserEvent` объект в качестве параметра.
### InAppBrowserEvent свойства
* **тип**: eventname, либо `loadstart` , `loadstop` , `loaderror` , или `exit` . *(Строка)*
* **URL**: URL-адрес, который был загружен. *(Строка)*
* **код**: код ошибки, только в случае `loaderror` . *(Число)*
* **сообщение**: сообщение об ошибке, только в случае `loaderror` . *(Строка)*
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* iOS
* Windows 8 и 8.1
* Windows Phone 7 и 8
### Краткий пример
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## метод removeEventListener
> Удаляет прослушиватель для события от`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ссылка**: ссылка для `InAppBrowser` окно. *(InAppBrowser)*
* **EventName**: событие прекратить прослушивание. *(Строка)*
* **loadstart**: событие возникает, когда `InAppBrowser` начинает для загрузки URL-адреса.
* **loadstop**: событие возникает, когда `InAppBrowser` завершит загрузку URL-адреса.
* **loaderror**: событие возникает, когда `InAppBrowser` обнаруживает ошибку загрузки URL-адреса.
* **выход**: возникает событие, когда `InAppBrowser` окно закрывается.
* **обратного вызова**: функция, выполняемая когда это событие наступает. Функция передается `InAppBrowserEvent` объект.
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* iOS
* Windows 8 и 8.1
* Windows Phone 7 и 8
### Краткий пример
var ref = window.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> Закрывает `InAppBrowser` окно.
Ref.Close();
* **ссылка**: ссылка на `InAppBrowser` окно *(InAppBrowser)*
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows 8 и 8.1
* Windows Phone 7 и 8
### Краткий пример
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> Отображается окно InAppBrowser, был открыт скрытые. Вызов это не имеет эффекта при InAppBrowser уже был виден.
Ref.Show();
* **ссылка**: ссылка на окно (InAppBrowser`InAppBrowser`)
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* iOS
* Windows 8 и 8.1
### Краткий пример
var ref = window.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Вставляет код JavaScript в `InAppBrowser` окно
ref.executeScript(details, callback);
* **ссылка**: ссылка на `InAppBrowser` окно. *(InAppBrowser)*
* **injectDetails**: подробности сценария для запуска, указав либо `file` или `code` ключ. *(Объект)*
* **файл**: URL-адрес сценария вставки.
* **код**: текст сценария для вставки.
* **обратного вызова**: функция, которая выполняет после вводят JavaScript-код.
* Если введенный скрипт имеет тип `code` , обратный вызов выполняется с одним параметром, который является возвращаемое значение сценария, завернутые в `Array` . Для многострочных сценариев это возвращаемое значение последнего оператора, или последнее вычисленное выражение.
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* iOS
* Windows 8 и 8.1
### Краткий пример
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
## insertCSS
> Внедряет CSS в `InAppBrowser` окно.
ref.insertCSS(details, callback);
* **ссылка**: ссылка на `InAppBrowser` окно *(InAppBrowser)*
* **injectDetails**: детали сценария для запуска, указав либо `file` или `code` ключ. *(Объект)*
* **файл**: URL-адрес таблицы стилей для вставки.
* **код**: текст таблицы стилей для вставки.
* **обратного вызова**: функция, которая выполняет после вводят CSS.
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* iOS
### Краткий пример
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,388 +0,0 @@
<!--
# 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.
-->
# cordova-plugin-inappbrowser
[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)
這個外掛程式提供了一個 web 瀏覽器視圖,顯示在調用 `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
`cordova.InAppBrowser.open()` 函數被定義為一個臨時替代 `window.open ()` 函數。 現有 `window.open ()` 調用,可以通過替換 window.open 使用 InAppBrowser 視窗:
window.open = cordova.InAppBrowser.open;
InAppBrowser 視窗像一個標準的 web 瀏覽器中,並且無法訪問科爾多瓦 Api。 為此,建議 InAppBrowser 如果您需要載入協力廠商 (不可信) 的內容,而不是載入,進入主要的科爾多瓦 web 視圖。 InAppBrowser 是不受白名單中,也不在系統瀏覽器中打開的連結。
InAppBrowser 預設情況下它自己的 GUI 控制項為使用者提供 (後退、 前進、 完成)。
為向後相容性,此外掛程式還鉤 `window.open`。 然而,`window.open` 外掛程式安裝鉤子可以有副作用 (尤其是如果這個外掛程式是只列為另一個外掛程式的依賴項)。 在未來的主要發行版本中,將刪除 `window.open` 鉤。 一直至從該外掛程式鉤子後,應用程式可以手動還原預設行為:
delete window.open // Reverts the call back to it's prototype's default
雖然 `window.open` 在全球範圍內InAppBrowser 不可用直到 `deviceready` 事件之後。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## 安裝
cordova plugin add cordova-plugin-inappbrowser
如果您希望所有頁面載入中您的應用程式要通過 InAppBrowser你可以簡單地在初始化過程中鉤 `window.open`。舉個例子:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
在新的 `InAppBrowser` 實例,當前的瀏覽器實例或系統瀏覽器中打開的 URL。
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref** 參考 `InAppBrowser` 視窗。*() InAppBrowser*
* **url** 要載入*(字串)*的 URL。調用 `encodeURI()` 這個如果 URL 包含 Unicode 字元。
* **target** 目標在其中載入的 URL可選參數預設值為 `_self` 。*(字串)*
* `_self` 打開在科爾多瓦 web 視圖如果 URL 是在白名單中,否則它在打開`InAppBrowser`.
* `_blank` 在打開`InAppBrowser`.
* `_system` 在該系統的 web 瀏覽器中打開。
* **options** 選項為 `InAppBrowser` 。可選,拖欠到: `location=yes` 。*(字串)*
`options`字串必須不包含任何空白的空間,和必須用逗號分隔每個功能的名稱/值對。 功能名稱區分大小寫。 所有平臺都支援下面的值:
* **location** 設置為 `yes``no` ,打開 `InAppBrowser` 的位置欄打開或關閉。
Android 系統只有:
* **hidden** 將設置為 `yes` ,創建瀏覽器和載入頁面,但不是顯示它。 載入完成時,將觸發 loadstop 事件。 省略或設置為 `no` (預設值),有的瀏覽器打開,然後以正常方式載入。
* **clearcache** 將設置為 `yes` 有瀏覽器的 cookie 清除緩存之前打開新視窗
* **clearsessioncache** 將設置為 `yes` 有會話 cookie 緩存清除之前打開新視窗
* **zoom**: 設置為`yes`,顯示 Android 瀏覽器的縮放控制項,設置為`no`,以隱藏它們。 `預設值是`.
* **hardwareback**: 設置為`yes`要使用硬體後退按鈕通過`InAppBrowser`的歷史向後導航。 如果沒有前一頁, `InAppBrowser`將會關閉。 預設值是的`yes`所以你必須將其設置為`no`,如果你想要的後退按鈕,只需關閉 InAppBrowser。
只有 iOS
* **closebuttoncaption**: 設置為一個字串,以用作**做**按鈕的標題。請注意您需要對此值進行當地語系化你自己。
* **disallowoverscroll** 將設置為 `yes``no` (預設值是 `no` )。打開/關閉的 UIWebViewBounce 屬性。
* **hidden** 將設置為 `yes` ,創建瀏覽器和載入頁面,但不是顯示它。 載入完成時,將觸發 loadstop 事件。 省略或設置為 `no` (預設值),有的瀏覽器打開,然後以正常方式載入。
* **clearcache** 將設置為 `yes` 有瀏覽器的 cookie 清除緩存之前打開新視窗
* **clearsessioncache** 將設置為 `yes` 有會話 cookie 緩存清除之前打開新視窗
* **toolbar** 設置為 `yes``no` ,為 InAppBrowser (預設為打開或關閉工具列`yes`)
* **enableViewportScale** 將設置為 `yes``no` ,防止通過 meta 標記 (預設為縮放的視區`no`).
* **mediaPlaybackRequiresUserAction** 將設置為 `yes``no` ,防止 HTML5 音訊或視頻從 autoplaying (預設為`no`).
* **allowInlineMediaPlayback** 將設置為 `yes``no` ,讓線在 HTML5 播放媒體,在瀏覽器視窗中,而不是特定于設備播放介面內顯示。 HTML 的 `video` 元素還必須包括 `webkit-playsinline` 屬性 (預設為`no`)
* **keyboardDisplayRequiresUserAction** 將設置為 `yes``no` 時,要打開鍵盤表單元素接收焦點通過 JavaScript 的 `focus()` 調用 (預設為`yes`).
* **suppressesIncrementalRendering** 將設置為 `yes``no` 等待,直到所有新查看的內容正在呈現 (預設為前收到`no`).
* **presentationstyle** 將設置為 `pagesheet` `formsheet``fullscreen` 來設置[演示文稿樣式](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle)(預設為`fullscreen`).
* **transitionstyle** 將設置為 `fliphorizontal` `crossdissolve``coververtical` 設置[過渡樣式](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle)(預設為`coververtical`).
* **toolbarposition** 將設置為 `top``bottom` (預設值是 `bottom` )。使工具列,則在頂部或底部的視窗。
僅限 Windows
* **hidden** 將設置為 `yes` ,創建瀏覽器和載入頁面,但不是顯示它。 載入完成時,將觸發 loadstop 事件。 省略或設置為 `no` (預設值),有的瀏覽器打開,然後以正常方式載入。
* **fullscreen**: 設置為`yes`,以創建無邊框的瀏覽器控制項。 請注意,如果**location=no**同時指定,則將呈現給使用者到密切 IAB 視窗沒有控制。
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* 火狐瀏覽器作業系統
* iOS
* Windows 8 和 8.1
* Windows Phone 7 和 8
* 瀏覽器
### 示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### 火狐瀏覽器作業系統的怪癖
外掛程式不會強制任何設計是需要添加一些 CSS 規則,如果打開與 `target=_blank`。規則 》 可能看起來像這些
```css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
```
### Windows 的怪癖
類似于 Firefox OS IAB 視窗視覺行為可以重寫通過`inAppBrowserWrap`/`inAppBrowserWrapFullscreen`的 CSS 類
### 瀏覽器的怪癖
* 外掛程式是通過 iframe執行
* 未實現導航歷史記錄 (在 LocationBar 的`回顧``展望`按鈕)。
## InAppBrowser
`科爾多瓦的調用返回的物件。InAppBrowser.open`.
### 方法
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> 為事件添加一個攔截器`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ref** 參考 `InAppBrowser` 視窗*(InAppBrowser)*
* **eventname** 事件偵聽*(字串)*
* **loadstart** 當觸發事件 `InAppBrowser` 開始載入一個 URL。
* **loadstop** 當觸發事件 `InAppBrowser` 完成載入一個 URL。
* **loaderror** 當觸發事件 `InAppBrowser` 載入 URL 時遇到錯誤。
* **exit** 當觸發事件 `InAppBrowser` 關閉視窗。
* **callback** 執行時觸發該事件的函數。該函數通過 `InAppBrowserEvent` 物件作為參數。
### InAppBrowserEvent 屬性
* **type** eventname或者 `loadstart` `loadstop` `loaderror` ,或 `exit` 。*(字串)*
* **url**: 已載入的 URL。*(字串)*
* **code** 僅中的情況的錯誤代碼 `loaderror` 。*(人數)*
* **message** 該錯誤訊息,只有在的情況下 `loaderror` 。*(字串)*
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* iOS
* Windows 8 和 8.1
* Windows Phone 7 和 8
* 瀏覽器
### 瀏覽器的怪癖
`loadstart``loaderror`的事件不會被觸發。
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> 移除的事件攔截器`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ref** 參考 `InAppBrowser` 視窗。*() InAppBrowser*
* **eventname** 要停止偵聽的事件。*(字串)*
* **loadstart** 當觸發事件 `InAppBrowser` 開始載入一個 URL。
* **loadstop** 當觸發事件 `InAppBrowser` 完成載入一個 URL。
* **loaderror** 當觸發事件 `InAppBrowser` 遇到錯誤載入一個 URL。
* **exit** 當觸發事件 `InAppBrowser` 關閉視窗。
* **callback**: 要在事件觸發時執行的函數。該函數通過 `InAppBrowserEvent` 物件。
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* iOS
* Windows 8 和 8.1
* Windows Phone 7 和 8
* 瀏覽器
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> 關閉 `InAppBrowser` 視窗。
ref.close();
* **ref** 參考 `InAppBrowser` 視窗*(InAppBrowser)*
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 火狐瀏覽器作業系統
* iOS
* Windows 8 和 8.1
* Windows Phone 7 和 8
* 瀏覽器
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> 顯示打開了隱藏的 InAppBrowser 視窗。調用這沒有任何影響,如果 InAppBrowser 是已經可見。
ref.show();
* **ref** InAppBrowser 視窗 (參考`InAppBrowser`)
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* iOS
* Windows 8 和 8.1
* 瀏覽器
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> 注入到 JavaScript 代碼 `InAppBrowser` 視窗
ref.executeScript(details, callback);
* **ref** 參考 `InAppBrowser` 視窗。*() InAppBrowser*
* **injectDetails**: 要運行的腳本的詳細資訊或指定 `file``code` 的關鍵。*(物件)*
* **檔** 腳本的 URL 來注入。
* **代碼** 要注入腳本的文本。
* **回檔** 執行後注入的 JavaScript 代碼的函數。
* 如果插入的腳本的類型 `code` ,回檔執行使用單個參數,這是該腳本的傳回值,裹在 `Array` 。 對於多行腳本,這是最後一條語句或最後計算的運算式的傳回值。
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* iOS
* Windows 8 和 8.1
* 瀏覽器
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### 瀏覽器的怪癖
* 只有**code**關鍵被支援。
### Windows 的怪癖
由於[MSDN 文檔](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx)調用的腳本可以返回唯一字串值,否則該參數,傳遞給**回檔**將是`[null]`.
## insertCSS
> 注入到 CSS `InAppBrowser` 視窗。
ref.insertCSS(details, callback);
* **ref** 參考 `InAppBrowser` 視窗*(InAppBrowser)*
* **injectDetails**: 要運行的腳本的詳細資訊或指定 `file``code` 的關鍵。*(物件)*
* **file** 樣式表的 URL 來注入。
* **code** 文本樣式表的注入。
* **callback** 在 CSS 注射後執行的函數。
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* iOS
* Windows
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,357 +0,0 @@
<!---
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.
-->
# cordova-plugin-inappbrowser
這個外掛程式提供了一個 web 瀏覽器視圖,顯示在調用 `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
`cordova.InAppBrowser.open()` 函數被定義為一個臨時替代 `window.open ()` 函數。 現有 `window.open ()` 調用,可以通過替換 window.open 使用 InAppBrowser 視窗:
window.open = cordova.InAppBrowser.open;
InAppBrowser 視窗像一個標準的 web 瀏覽器中,並且無法訪問科爾多瓦 Api。 為此,建議 InAppBrowser 如果您需要載入協力廠商 (不可信) 的內容,而不是載入,進入主要的科爾多瓦 web 視圖。 InAppBrowser 是不受白名單中,也不在系統瀏覽器中打開的連結。
InAppBrowser 預設情況下它自己的 GUI 控制項為使用者提供 (後退、 前進、 完成)。
為向後相容性,此外掛程式還鉤 `window.open`。 然而,`window.open` 外掛程式安裝鉤子可以有副作用 (尤其是如果這個外掛程式是只列為另一個外掛程式的依賴項)。 在未來的主要發行版本中,將刪除 `window.open` 鉤。 一直至從該外掛程式鉤子後,應用程式可以手動還原預設行為:
delete window.open // Reverts the call back to it's prototype's default
雖然 `window.open` 在全球範圍內InAppBrowser 不可用直到 `deviceready` 事件之後。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## 安裝
cordova plugin add cordova-plugin-inappbrowser
如果您希望所有頁面載入中您的應用程式要通過 InAppBrowser你可以簡單地在初始化過程中鉤 `window.open`。舉個例子:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
在新的 `InAppBrowser` 實例,當前的瀏覽器實例或系統瀏覽器中打開的 URL。
var ref = cordova.InAppBrowser.open(url, target, options);
* **ref** 參考 `InAppBrowser` 視窗。*() InAppBrowser*
* **url** 要載入*(字串)*的 URL。調用 `encodeURI()` 這個如果 URL 包含 Unicode 字元。
* **target** 目標在其中載入的 URL可選參數預設值為 `_self` 。*(字串)*
* `_self` 打開在科爾多瓦 web 視圖如果 URL 是在白名單中,否則它在打開`InAppBrowser`.
* `_blank` 在打開`InAppBrowser`.
* `_system` 在該系統的 web 瀏覽器中打開。
* **options** 選項為 `InAppBrowser` 。可選,拖欠到: `location=yes` 。*(字串)*
`options`字串必須不包含任何空白的空間,和必須用逗號分隔每個功能的名稱/值對。 功能名稱區分大小寫。 所有平臺都支援下面的值:
* **location** 設置為 `yes``no` ,打開 `InAppBrowser` 的位置欄打開或關閉。
Android 系統只有:
* **hidden** 將設置為 `yes` ,創建瀏覽器和載入頁面,但不是顯示它。 載入完成時,將觸發 loadstop 事件。 省略或設置為 `no` (預設值),有的瀏覽器打開,然後以正常方式載入。
* **clearcache** 將設置為 `yes` 有瀏覽器的 cookie 清除緩存之前打開新視窗
* **clearsessioncache** 將設置為 `yes` 有會話 cookie 緩存清除之前打開新視窗
只有 iOS
* **closebuttoncaption**: 設置為一個字串,以用作**做**按鈕的標題。請注意您需要對此值進行當地語系化你自己。
* **disallowoverscroll** 將設置為 `yes``no` (預設值是 `no` )。打開/關閉的 UIWebViewBounce 屬性。
* **hidden** 將設置為 `yes` ,創建瀏覽器和載入頁面,但不是顯示它。 載入完成時,將觸發 loadstop 事件。 省略或設置為 `no` (預設值),有的瀏覽器打開,然後以正常方式載入。
* **clearcache** 將設置為 `yes` 有瀏覽器的 cookie 清除緩存之前打開新視窗
* **clearsessioncache** 將設置為 `yes` 有會話 cookie 緩存清除之前打開新視窗
* **toolbar** 設置為 `yes``no` ,為 InAppBrowser (預設為打開或關閉工具列`yes`)
* **enableViewportScale** 將設置為 `yes``no` ,防止通過 meta 標記 (預設為縮放的視區`no`).
* **mediaPlaybackRequiresUserAction** 將設置為 `yes``no` ,防止 HTML5 音訊或視頻從 autoplaying (預設為`no`).
* **allowInlineMediaPlayback** 將設置為 `yes``no` ,讓線在 HTML5 播放媒體,在瀏覽器視窗中,而不是特定于設備播放介面內顯示。 HTML 的 `video` 元素還必須包括 `webkit-playsinline` 屬性 (預設為`no`)
* **keyboardDisplayRequiresUserAction** 將設置為 `yes``no` 時,要打開鍵盤表單元素接收焦點通過 JavaScript 的 `focus()` 調用 (預設為`yes`).
* **suppressesIncrementalRendering** 將設置為 `yes``no` 等待,直到所有新查看的內容正在呈現 (預設為前收到`no`).
* **presentationstyle** 將設置為 `pagesheet` `formsheet``fullscreen` 來設置[演示文稿樣式][1](預設為`fullscreen`).
* **transitionstyle** 將設置為 `fliphorizontal` `crossdissolve``coververtical` 設置[過渡樣式][2](預設為`coververtical`).
* **toolbarposition** 將設置為 `top``bottom` (預設值是 `bottom` )。使工具列,則在頂部或底部的視窗。
僅限 Windows
* **hidden** 將設置為 `yes` ,創建瀏覽器並載入頁面,但不是顯示它。 載入完成時,將觸發 loadstop 事件。 省略或被設置為 `no` (預設值),有的瀏覽器打開,以正常方式載入。
[1]: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle
[2]: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* 火狐瀏覽器的作業系統
* iOS
* Windows 8 和 8.1
* Windows Phone 7 和 8
### 示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### 火狐瀏覽器作業系統的怪癖
外掛程式不會強制任何設計是需要添加一些 CSS 規則,如果打開與 `target=_blank`。規則 》 可能看起來像這些
css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
## InAppBrowser
`科爾多瓦的調用返回的物件。InAppBrowser.open`.
### 方法
* addEventListener
* removeEventListener
* close
* show
* executeScript
* insertCSS
## addEventListener
> 為事件添加一個攔截器`InAppBrowser`.
ref.addEventListener(eventname, callback);
* **ref** 參考 `InAppBrowser` 視窗*(InAppBrowser)*
* **eventname** 事件偵聽*(字串)*
* **loadstart** 當觸發事件 `InAppBrowser` 開始載入一個 URL。
* **loadstop** 當觸發事件 `InAppBrowser` 完成載入一個 URL。
* **loaderror** 當觸發事件 `InAppBrowser` 載入 URL 時遇到錯誤。
* **exit** 當觸發事件 `InAppBrowser` 關閉視窗。
* **callback** 執行時觸發該事件的函數。該函數通過 `InAppBrowserEvent` 物件作為參數。
### InAppBrowserEvent 屬性
* **type** eventname或者 `loadstart` `loadstop` `loaderror` ,或 `exit` 。*(字串)*
* **url**: 已載入的 URL。*(字串)*
* **code** 僅中的情況的錯誤代碼 `loaderror` 。*(人數)*
* **message** 該錯誤訊息,只有在的情況下 `loaderror` 。*(字串)*
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* iOS
* Windows 8 和 8.1
* Windows Phone 7 和 8
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> 移除的事件攔截器`InAppBrowser`.
ref.removeEventListener(eventname, callback);
* **ref** 參考 `InAppBrowser` 視窗。*() InAppBrowser*
* **eventname** 要停止偵聽的事件。*(字串)*
* **loadstart** 當觸發事件 `InAppBrowser` 開始載入一個 URL。
* **loadstop** 當觸發事件 `InAppBrowser` 完成載入一個 URL。
* **loaderror** 當觸發事件 `InAppBrowser` 遇到錯誤載入一個 URL。
* **exit** 當觸發事件 `InAppBrowser` 關閉視窗。
* **callback**: 要在事件觸發時執行的函數。該函數通過 `InAppBrowserEvent` 物件。
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* iOS
* Windows 8 和 8.1
* Windows Phone 7 和 8
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> 關閉 `InAppBrowser` 視窗。
ref.close();
* **ref** 參考 `InAppBrowser` 視窗*(InAppBrowser)*
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 火狐瀏覽器的作業系統
* iOS
* Windows 8 和 8.1
* Windows Phone 7 和 8
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> 顯示打開了隱藏的 InAppBrowser 視窗。調用這沒有任何影響,如果 InAppBrowser 是已經可見。
ref.show();
* **ref** InAppBrowser 視窗 (參考`InAppBrowser`)
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* iOS
* Windows 8 和 8.1
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> 注入到 JavaScript 代碼 `InAppBrowser` 視窗
ref.executeScript(details, callback);
* **ref** 參考 `InAppBrowser` 視窗。*() InAppBrowser*
* **injectDetails**: 要運行的腳本的詳細資訊或指定 `file``code` 的關鍵。*(物件)*
* **檔** 腳本的 URL 來注入。
* **代碼** 要注入腳本的文本。
* **回檔** 執行後注入的 JavaScript 代碼的函數。
* 如果插入的腳本的類型 `code` ,回檔執行使用單個參數,這是該腳本的傳回值,裹在 `Array` 。 對於多行腳本,這是最後一條語句或最後計算的運算式的傳回值。
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* iOS
* Windows 8 和 8.1
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
## insertCSS
> 注入到 CSS `InAppBrowser` 視窗。
ref.insertCSS(details, callback);
* **ref** 參考 `InAppBrowser` 視窗*(InAppBrowser)*
* **injectDetails**: 要運行的腳本的詳細資訊或指定 `file``code` 的關鍵。*(物件)*
* **file** 樣式表的 URL 來注入。
* **code** 文本樣式表的注入。
* **callback** 在 CSS 注射後執行的函數。
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* iOS
### 快速的示例
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -1,27 +1,25 @@
{
"name": "cordova-plugin-inappbrowser",
"version": "1.6.2-dev",
"version": "4.0.0",
"description": "Cordova InAppBrowser Plugin",
"types": "./types/index.d.ts",
"cordova": {
"id": "cordova-plugin-inappbrowser",
"platforms": [
"android",
"amazon-fireos",
"ubuntu",
"browser",
"ios",
"osx",
"wp7",
"wp8",
"windows8",
"windows",
"firefoxos"
"windows"
]
},
"repository": {
"type": "git",
"url": "https://github.com/apache/cordova-plugin-inappbrowser"
},
"bugs": {
"url": "https://github.com/apache/cordova-plugin-inappbrowser/issues"
},
"keywords": [
"cordova",
"in",
@@ -30,26 +28,25 @@
"inappbrowser",
"ecosystem:cordova",
"cordova-android",
"cordova-amazon-fireos",
"cordova-ubuntu",
"cordova-browser",
"cordova-ios",
"cordova-osx",
"cordova-wp7",
"cordova-wp8",
"cordova-windows8",
"cordova-windows",
"cordova-firefoxos"
"cordova-windows"
],
"scripts": {
"test": "npm run jshint",
"jshint": "node node_modules/jshint/bin/jshint www && node node_modules/jshint/bin/jshint src && node node_modules/jshint/bin/jshint tests"
"test": "npm run eslint",
"eslint": "node node_modules/eslint/bin/eslint www && node node_modules/eslint/bin/eslint src && node node_modules/eslint/bin/eslint tests"
},
"engines": {
"cordovaDependencies": {
"0.2.3": {
"cordova": ">=3.1.0"
},
"2.0.0": {
"4.0.0": {
"cordova": ">=3.1.0",
"cordova-ios": ">=4.0.0"
},
"5.0.0": {
"cordova": ">100"
}
}
@@ -57,6 +54,12 @@
"author": "Apache Software Foundation",
"license": "Apache-2.0",
"devDependencies": {
"jshint": "^2.6.0"
"eslint": "^4.0.0",
"eslint-config-semistandard": "^11.0.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.3.0",
"eslint-plugin-node": "^5.0.0",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1"
}
}

View File

@@ -20,27 +20,27 @@
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="cordova-plugin-inappbrowser"
version="1.6.2-dev">
version="4.0.0">
<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>
<repo>https://github.com/apache/cordova-plugin-inappbrowser</repo>
<issue>https://github.com/apache/cordova-plugin-inappbrowser/issues</issue>
<engines>
<engine name="cordova" version=">=3.1.0" /><!-- Needs cordova/urlutil -->
<engine name="cordova-ios" version=">=4.0.0" />
</engines>
<!-- android -->
<platform name="android">
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
<config-file target="res/xml/config.xml" parent="/*">
<feature name="InAppBrowser">
<feature name="InAppBrowser">
<param name="android-package" value="org.apache.cordova.inappbrowser.InAppBrowser"/>
</feature>
</config-file>
@@ -49,7 +49,7 @@
<source-file src="src/android/InAppBrowserDialog.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 -->
<!-- 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" />
@@ -67,67 +67,26 @@
</platform>
<!-- amazon-fireos -->
<platform name="amazon-fireos">
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
<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/android/InAppBrowserDialog.java" target-dir="src/org/apache/cordova/inappbrowser" />
<source-file src="src/amazon/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>
<!-- ubuntu -->
<platform name="ubuntu">
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
<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/InAppBrowser_escapeScript.js" />
<resource-file src="src/ubuntu/close.png" />
</platform>
<!-- ios -->
<platform name="ios">
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
</js-module>
<config-file target="config.xml" parent="/*">
<feature name="InAppBrowser">
<param name="ios-package" value="CDVInAppBrowser" />
<param name="ios-package" value="CDVWKInAppBrowser" />
<param name="onload" value="true" />
</feature>
</config-file>
<header-file src="src/ios/CDVInAppBrowserOptions.h" />
<source-file src="src/ios/CDVInAppBrowserOptions.m" />
<header-file src="src/ios/CDVInAppBrowserNavigationController.h" />
<source-file src="src/ios/CDVInAppBrowserNavigationController.m" />
<header-file src="src/ios/CDVWKInAppBrowser.h" />
<source-file src="src/ios/CDVWKInAppBrowser.m" />
<header-file src="src/ios/CDVWKInAppBrowserUIDelegate.h" />
<source-file src="src/ios/CDVWKInAppBrowserUIDelegate.m" />
<header-file src="src/ios/CDVInAppBrowser.h" />
<source-file src="src/ios/CDVInAppBrowser.m" />
<framework src="CoreGraphics.framework" />
</platform>
@@ -135,7 +94,6 @@
<platform name="osx">
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
<config-file target="config.xml" parent="/*">
<feature name="InAppBrowser">
@@ -147,68 +105,10 @@
<source-file src="src/osx/CDVInAppBrowser.m" />
</platform>
<!-- wp7 -->
<platform name="wp7">
<config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities">
<Capability Name="ID_CAP_NETWORKING"/>
</config-file>
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
<config-file target="config.xml" parent="/*">
<feature name="InAppBrowser">
<param name="wp-package" value="InAppBrowser"/>
</feature>
</config-file>
<config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities">
<Capability Name="ID_CAP_NETWORKING" />
</config-file>
<source-file src="src/wp/InAppBrowser.cs" />
</platform>
<!-- wp8 -->
<platform name="wp8">
<config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities">
<Capability Name="ID_CAP_NETWORKING"/>
</config-file>
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
<config-file target="config.xml" parent="/*">
<feature name="InAppBrowser">
<param name="wp-package" value="InAppBrowser"/>
</feature>
</config-file>
<config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities">
<Capability Name="ID_CAP_NETWORKING" />
</config-file>
<source-file src="src/wp/InAppBrowser.cs" />
</platform>
<!-- windows8 -->
<platform name="windows8">
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
<js-module src="www/windows8/InAppBrowserProxy.js" name="InAppBrowserProxy">
<merges target="" />
</js-module>
</platform>
<!-- windows universal apps (Windows 8.1, Windows Phone 8.1, Windows 8.0) -->
<!-- windows -->
<platform name="windows">
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
<js-module src="src/windows/InAppBrowserProxy.js" name="InAppBrowserProxy">
<runs />
@@ -216,25 +116,10 @@
<asset src="www/inappbrowser.css" target="css/inappbrowser.css" />
</platform>
<!-- firefoxos -->
<platform name="firefoxos">
<config-file target="config.xml" parent="/*">
<permission name="browser" description="Enables the app to implement a browser in an iframe." privileged="true"/>
</config-file>
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
<js-module src="src/firefoxos/InAppBrowserProxy.js" name="InAppBrowserProxy">
<runs />
</js-module>
</platform>
<!-- browser -->
<platform name="browser">
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
<clobbers target="window.open" />
</js-module>
<js-module src="src/browser/InAppBrowserProxy.js" name="InAppBrowserProxy">
<runs />

View File

@@ -1,879 +0,0 @@
/*
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 org.apache.cordova.inappbrowser.InAppBrowserDialog;
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 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 ZOOM = "zoom";
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 CLEAR_ALL_CACHE = "clearcache";
private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
private static final String HARDWARE_BACK_BUTTON = "hardwareback";
private InAppBrowserDialog dialog;
private AmazonWebView inAppWebView;
private EditText edittext;
private CallbackContext callbackContext;
private boolean showLocationBar = true;
private boolean showZoomControls = true;
private boolean openWindowHidden = false;
private boolean clearAllCache= false;
private boolean clearSessionCache=false;
private boolean hadwareBackButton=true;
/**
* 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)) {
Log.d(LOG_TAG, "loading in webview");
webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(AmazonWebView.SCHEME_TEL))
{
try {
Log.d(LOG_TAG, "loading in dialer");
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 {
Log.d(LOG_TAG, "loading in InAppBrowser");
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 if (action.equals("hide")) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.hide();
}
});
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.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();
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 AmazonWebView 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.setWebViewClient(new AmazonWebViewClient() {
// NB: wait for about:blank before dismissing
public void onPageFinished(AmazonWebView view, String url) {
if (dialog != null) {
dialog.dismiss();
}
}
});
// 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");
}
});
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.
*/
public void goBack() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (InAppBrowser.this.inAppWebView.canGoBack()) {
InAppBrowser.this.inAppWebView.goBack();
}
}
});
}
/**
* Can the web browser go back?
* @return boolean
*/
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
/**
* Has the user set the hardware back button to go back
* @return boolean
*/
public boolean hardwareBack() {
return hadwareBackButton;
}
/**
* 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;
}
/**
* Should we show the zoom controls?
*
* @return boolean
*/
private boolean getShowZoomControls() {
return this.showZoomControls;
}
private InAppBrowser getInAppBrowser(){
return this;
}
/**
* 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;
showZoomControls = true;
openWindowHidden = false;
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
Boolean zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.booleanValue();
}
Boolean hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.booleanValue();
}
Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.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;
}
@SuppressLint("NewApi")
public void run() {
// Let's create the main dialog
dialog = new InAppBrowserDialog(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.setInAppBroswer(getInAppBrowser());
// 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);
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);
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/Done 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);
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 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(getShowZoomControls());
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");
}
}
}
}

View File

@@ -1,146 +0,0 @@
/*
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 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;
}
}

View File

@@ -19,12 +19,21 @@
package org.apache.cordova.inappbrowser;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Parcelable;
import android.provider.Browser;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Color;
import android.net.http.SslError;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
@@ -41,8 +50,12 @@ import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@@ -51,6 +64,7 @@ import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.Config;
@@ -67,6 +81,9 @@ import org.json.JSONObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.StringTokenizer;
@@ -84,6 +101,7 @@ public class InAppBrowser extends CordovaPlugin {
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 MESSAGE_EVENT = "message";
private static final String CLEAR_ALL_CACHE = "clearcache";
private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
private static final String HARDWARE_BACK_BUTTON = "hardwareback";
@@ -91,6 +109,19 @@ public class InAppBrowser extends CordovaPlugin {
private static final String SHOULD_PAUSE = "shouldPauseOnSuspend";
private static final Boolean DEFAULT_HARDWARE_BACK = true;
private static final String USER_WIDE_VIEW_PORT = "useWideViewPort";
private static final String TOOLBAR_COLOR = "toolbarcolor";
private static final String CLOSE_BUTTON_CAPTION = "closebuttoncaption";
private static final String CLOSE_BUTTON_COLOR = "closebuttoncolor";
private static final String LEFT_TO_RIGHT = "lefttoright";
private static final String HIDE_NAVIGATION = "hidenavigationbuttons";
private static final String NAVIGATION_COLOR = "navigationbuttoncolor";
private static final String HIDE_URL = "hideurlbar";
private static final String FOOTER = "footer";
private static final String FOOTER_COLOR = "footercolor";
private static final String BEFORELOAD = "beforeload";
private static final String FULLSCREEN = "fullscreen";
private static final List customizableOptions = Arrays.asList(CLOSE_BUTTON_CAPTION, TOOLBAR_COLOR, NAVIGATION_COLOR, CLOSE_BUTTON_COLOR, FOOTER_COLOR);
private InAppBrowserDialog dialog;
private WebView inAppWebView;
@@ -109,6 +140,19 @@ public class InAppBrowser extends CordovaPlugin {
private ValueCallback<Uri[]> mUploadCallbackLollipop;
private final static int FILECHOOSER_REQUESTCODE = 1;
private final static int FILECHOOSER_REQUESTCODE_LOLLIPOP = 2;
private String closeButtonCaption = "";
private String closeButtonColor = "";
private boolean leftToRight = false;
private int toolbarColor = android.graphics.Color.LTGRAY;
private boolean hideNavigationButtons = false;
private String navigationButtonColor = "";
private boolean hideUrlBar = false;
private boolean showFooter = false;
private String footerColor = "";
private String beforeload = "";
private boolean fullscreen = true;
private String[] allowedSchemes;
private InAppBrowserClient currentClient;
/**
* Executes the request and returns PluginResult.
@@ -127,7 +171,7 @@ public class InAppBrowser extends CordovaPlugin {
t = SELF;
}
final String target = t;
final HashMap<String, Boolean> features = parseFeature(args.optString(2));
final HashMap<String, String> features = parseFeature(args.optString(2));
LOG.d(LOG_TAG, "target = " + target);
@@ -216,6 +260,25 @@ public class InAppBrowser extends CordovaPlugin {
else if (action.equals("close")) {
closeDialog();
}
else if (action.equals("loadAfterBeforeload")) {
if (beforeload == null) {
LOG.e(LOG_TAG, "unexpected loadAfterBeforeload called without feature beforeload=yes");
}
final String url = args.getString(0);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) {
currentClient.waitForBeforeload = false;
inAppWebView.setWebViewClient(currentClient);
} else {
((InAppBrowserClient)inAppWebView.getWebViewClient()).waitForBeforeload = false;
}
inAppWebView.loadUrl(url);
}
});
}
else if (action.equals("injectScriptCode")) {
String jsWrapper = null;
if (args.getBoolean(1)) {
@@ -254,7 +317,9 @@ public class InAppBrowser extends CordovaPlugin {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.show();
if (dialog != null && !cordova.getActivity().isFinishing()) {
dialog.show();
}
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
@@ -265,7 +330,9 @@ public class InAppBrowser extends CordovaPlugin {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.hide();
if (dialog != null && !cordova.getActivity().isFinishing()) {
dialog.hide();
}
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
@@ -366,18 +433,21 @@ public class InAppBrowser extends CordovaPlugin {
* @param optString
* @return
*/
private HashMap<String, Boolean> parseFeature(String optString) {
private HashMap<String, String> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
HashMap<String, String> map = new HashMap<String, String>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
String value = option.nextToken();
if (!customizableOptions.contains(key)) {
value = value.equals("yes") || value.equals("no") ? value : "yes";
}
map.put(key, value);
}
}
@@ -404,15 +474,56 @@ public class InAppBrowser extends CordovaPlugin {
intent.setData(uri);
}
intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName());
this.cordova.getActivity().startActivity(intent);
// CB-10795: Avoid circular loops by preventing it from opening in the current app
this.openExternalExcludeCurrentApp(intent);
return "";
// not catching FileUriExposedException explicitly because buildtools<24 doesn't know about it
// not catching FileUriExposedException explicitly because buildtools<24 doesn't know about it
} catch (java.lang.RuntimeException e) {
LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString());
return e.toString();
}
}
/**
* Opens the intent, providing a chooser that excludes the current app to avoid
* circular loops.
*/
private void openExternalExcludeCurrentApp(Intent intent) {
String currentPackage = cordova.getActivity().getPackageName();
boolean hasCurrentPackage = false;
PackageManager pm = cordova.getActivity().getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
ArrayList<Intent> targetIntents = new ArrayList<Intent>();
for (ResolveInfo ri : activities) {
if (!currentPackage.equals(ri.activityInfo.packageName)) {
Intent targetIntent = (Intent)intent.clone();
targetIntent.setPackage(ri.activityInfo.packageName);
targetIntents.add(targetIntent);
}
else {
hasCurrentPackage = true;
}
}
// If the current app package isn't a target for this URL, then use
// the normal launch behavior
if (hasCurrentPackage == false || targetIntents.size() == 0) {
this.cordova.getActivity().startActivity(intent);
}
// If there's only one possible intent, launch it directly
else if (targetIntents.size() == 1) {
this.cordova.getActivity().startActivity(targetIntents.get(0));
}
// Otherwise, show a custom chooser without the current app listed
else if (targetIntents.size() > 0) {
Intent chooser = Intent.createChooser(targetIntents.remove(targetIntents.size()-1), null);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toArray(new Parcelable[] {}));
this.cordova.getActivity().startActivity(chooser);
}
}
/**
* Closes the dialog
*/
@@ -430,7 +541,7 @@ public class InAppBrowser extends CordovaPlugin {
childView.setWebViewClient(new WebViewClient() {
// NB: wait for about:blank before dismissing
public void onPageFinished(WebView view, String url) {
if (dialog != null) {
if (dialog != null && !cordova.getActivity().isFinishing()) {
dialog.dismiss();
dialog = null;
}
@@ -513,7 +624,7 @@ public class InAppBrowser extends CordovaPlugin {
return this.showLocationBar;
}
private InAppBrowser getInAppBrowser(){
private InAppBrowser getInAppBrowser() {
return this;
}
@@ -523,7 +634,7 @@ public class InAppBrowser extends CordovaPlugin {
* @param url the url to load.
* @param features jsonObject
*/
public String showWebPage(final String url, HashMap<String, Boolean> features) {
public String showWebPage(final String url, HashMap<String, String> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
@@ -531,44 +642,84 @@ public class InAppBrowser extends CordovaPlugin {
mediaPlaybackRequiresUserGesture = false;
if (features != null) {
Boolean show = features.get(LOCATION);
String show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
showLocationBar = show.equals("yes") ? true : false;
}
Boolean zoom = features.get(ZOOM);
if(showLocationBar) {
String hideNavigation = features.get(HIDE_NAVIGATION);
String hideUrl = features.get(HIDE_URL);
if(hideNavigation != null) hideNavigationButtons = hideNavigation.equals("yes") ? true : false;
if(hideUrl != null) hideUrlBar = hideUrl.equals("yes") ? true : false;
}
String zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.booleanValue();
showZoomControls = zoom.equals("yes") ? true : false;
}
Boolean hidden = features.get(HIDDEN);
String hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.booleanValue();
openWindowHidden = hidden.equals("yes") ? true : false;
}
Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
String hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.booleanValue();
hadwareBackButton = hardwareBack.equals("yes") ? true : false;
} else {
hadwareBackButton = DEFAULT_HARDWARE_BACK;
}
Boolean mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION);
String mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION);
if (mediaPlayback != null) {
mediaPlaybackRequiresUserGesture = mediaPlayback.booleanValue();
mediaPlaybackRequiresUserGesture = mediaPlayback.equals("yes") ? true : false;
}
Boolean cache = features.get(CLEAR_ALL_CACHE);
String cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.booleanValue();
clearAllCache = cache.equals("yes") ? true : false;
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.booleanValue();
clearSessionCache = cache.equals("yes") ? true : false;
}
}
Boolean shouldPause = features.get(SHOULD_PAUSE);
String shouldPause = features.get(SHOULD_PAUSE);
if (shouldPause != null) {
shouldPauseInAppBrowser = shouldPause.booleanValue();
shouldPauseInAppBrowser = shouldPause.equals("yes") ? true : false;
}
Boolean wideViewPort = features.get(USER_WIDE_VIEW_PORT);
String wideViewPort = features.get(USER_WIDE_VIEW_PORT);
if (wideViewPort != null ) {
useWideViewPort = wideViewPort.booleanValue();
useWideViewPort = wideViewPort.equals("yes") ? true : false;
}
String closeButtonCaptionSet = features.get(CLOSE_BUTTON_CAPTION);
if (closeButtonCaptionSet != null) {
closeButtonCaption = closeButtonCaptionSet;
}
String closeButtonColorSet = features.get(CLOSE_BUTTON_COLOR);
if (closeButtonColorSet != null) {
closeButtonColor = closeButtonColorSet;
}
String leftToRightSet = features.get(LEFT_TO_RIGHT);
leftToRight = leftToRightSet != null && leftToRightSet.equals("yes");
String toolbarColorSet = features.get(TOOLBAR_COLOR);
if (toolbarColorSet != null) {
toolbarColor = android.graphics.Color.parseColor(toolbarColorSet);
}
String navigationButtonColorSet = features.get(NAVIGATION_COLOR);
if (navigationButtonColorSet != null) {
navigationButtonColor = navigationButtonColorSet;
}
String showFooterSet = features.get(FOOTER);
if (showFooterSet != null) {
showFooter = showFooterSet.equals("yes") ? true : false;
}
String footerColorSet = features.get(FOOTER_COLOR);
if (footerColorSet != null) {
footerColor = footerColorSet;
}
if (features.get(BEFORELOAD) != null) {
beforeload = features.get(BEFORELOAD);
}
String fullscreenSet = features.get(FULLSCREEN);
if (fullscreenSet != null) {
fullscreen = fullscreenSet.equals("yes") ? true : false;
}
}
@@ -583,13 +734,61 @@ public class InAppBrowser extends CordovaPlugin {
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
private View createCloseButton(int id) {
View _close;
Resources activityRes = cordova.getActivity().getResources();
if (closeButtonCaption != "") {
// Use TextView for text
TextView close = new TextView(cordova.getActivity());
close.setText(closeButtonCaption);
close.setTextSize(20);
if (closeButtonColor != "") close.setTextColor(android.graphics.Color.parseColor(closeButtonColor));
close.setGravity(android.view.Gravity.CENTER_VERTICAL);
close.setPadding(this.dpToPixels(10), 0, this.dpToPixels(10), 0);
_close = close;
}
else {
ImageButton close = new ImageButton(cordova.getActivity());
int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
Drawable closeIcon = activityRes.getDrawable(closeResId);
if (closeButtonColor != "") close.setColorFilter(android.graphics.Color.parseColor(closeButtonColor));
close.setImageDrawable(closeIcon);
close.setScaleType(ImageView.ScaleType.FIT_CENTER);
if (Build.VERSION.SDK_INT >= 16)
close.getAdjustViewBounds();
_close = close;
}
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
if (leftToRight) closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
else closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
_close.setLayoutParams(closeLayoutParams);
if (Build.VERSION.SDK_INT >= 16)
_close.setBackground(null);
else
_close.setBackgroundDrawable(null);
_close.setContentDescription("Close Button");
_close.setId(Integer.valueOf(id));
_close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
return _close;
}
@SuppressLint("NewApi")
public void run() {
@@ -602,6 +801,9 @@ public class InAppBrowser extends CordovaPlugin {
dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (fullscreen) {
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
dialog.setCancelable(true);
dialog.setInAppBroswer(getInAppBrowser());
@@ -612,18 +814,25 @@ public class InAppBrowser extends CordovaPlugin {
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
//Please, no more black!
toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
toolbar.setBackgroundColor(toolbarColor);
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);
if (leftToRight) {
toolbar.setHorizontalGravity(Gravity.LEFT);
} else {
toolbar.setHorizontalGravity(Gravity.RIGHT);
}
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));
RelativeLayout.LayoutParams actionButtonLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (leftToRight) actionButtonLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
else actionButtonLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
actionButtonContainer.setLayoutParams(actionButtonLayoutParams);
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(Integer.valueOf(1));
actionButtonContainer.setId(leftToRight ? Integer.valueOf(5) : Integer.valueOf(1));
// Back button
ImageButton back = new ImageButton(cordova.getActivity());
@@ -635,6 +844,7 @@ public class InAppBrowser extends CordovaPlugin {
Resources activityRes = cordova.getActivity().getResources();
int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
Drawable backIcon = activityRes.getDrawable(backResId);
if (navigationButtonColor != "") back.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
if (Build.VERSION.SDK_INT >= 16)
back.setBackground(null);
else
@@ -660,6 +870,7 @@ public class InAppBrowser extends CordovaPlugin {
forward.setId(Integer.valueOf(3));
int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
Drawable fwdIcon = activityRes.getDrawable(fwdResId);
if (navigationButtonColor != "") forward.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
if (Build.VERSION.SDK_INT >= 16)
forward.setBackground(null);
else
@@ -692,37 +903,38 @@ public class InAppBrowser extends CordovaPlugin {
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;
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close/Done button
ImageButton close = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
close.setContentDescription("Close Button");
close.setId(Integer.valueOf(5));
int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
Drawable closeIcon = activityRes.getDrawable(closeResId);
if (Build.VERSION.SDK_INT >= 16)
close.setBackground(null);
else
close.setBackgroundDrawable(null);
close.setImageDrawable(closeIcon);
close.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
close.getAdjustViewBounds();
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// Header Close/Done button
int closeButtonId = leftToRight ? 1 : 5;
View close = createCloseButton(closeButtonId);
toolbar.addView(close);
// Footer
RelativeLayout footer = new RelativeLayout(cordova.getActivity());
int _footerColor;
if(footerColor != "") {
_footerColor = Color.parseColor(footerColor);
} else {
_footerColor = android.graphics.Color.LTGRAY;
}
footer.setBackgroundColor(_footerColor);
RelativeLayout.LayoutParams footerLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44));
footerLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
footer.setLayoutParams(footerLayout);
if (closeButtonCaption != "") footer.setPadding(this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8));
footer.setHorizontalGravity(Gravity.LEFT);
footer.setVerticalGravity(Gravity.BOTTOM);
View footerClose = createCloseButton(7);
footer.addView(footerClose);
// WebView
inAppWebView = new WebView(cordova.getActivity());
@@ -771,16 +983,32 @@ public class InAppBrowser extends CordovaPlugin {
}
});
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
currentClient = new InAppBrowserClient(thatWebView, edittext, beforeload);
inAppWebView.setWebViewClient(currentClient);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(showZoomControls);
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
// Add postMessage interface
class JsObject {
@JavascriptInterface
public void postMessage(String data) {
try {
JSONObject obj = new JSONObject();
obj.put("type", MESSAGE_EVENT);
obj.put("data", new JSONObject(data));
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.e(LOG_TAG, "data object passed to postMessage has caused a JSON error.");
}
}
}
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
inAppWebView.addJavascriptInterface(new JsObject(), "cordova_iab");
}
String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
@@ -809,6 +1037,11 @@ public class InAppBrowser extends CordovaPlugin {
CookieManager.getInstance().removeSessionCookie();
}
// Enable Thirdparty Cookies on >=Android 5.0 device
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(inAppWebView,true);
}
inAppWebView.loadUrl(url);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
@@ -820,10 +1053,9 @@ public class InAppBrowser extends CordovaPlugin {
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Add the views to our toolbar if they haven't been disabled
if (!hideNavigationButtons) toolbar.addView(actionButtonContainer);
if (!hideUrlBar) toolbar.addView(edittext);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
@@ -832,19 +1064,28 @@ public class InAppBrowser extends CordovaPlugin {
}
// Add our webview to our main view/layout
main.addView(inAppWebView);
RelativeLayout webViewLayout = new RelativeLayout(cordova.getActivity());
webViewLayout.addView(inAppWebView);
main.addView(webViewLayout);
// Don't add the footer unless it's been enabled
if (showFooter) {
webViewLayout.addView(footer);
}
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);
if (dialog != null) {
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) {
if (openWindowHidden && dialog != null) {
dialog.hide();
}
}
@@ -921,6 +1162,8 @@ public class InAppBrowser extends CordovaPlugin {
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
String beforeload;
boolean waitForBeforeload;
/**
* Constructor.
@@ -928,9 +1171,41 @@ public class InAppBrowser extends CordovaPlugin {
* @param webView
* @param mEditText
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
public InAppBrowserClient(CordovaWebView webView, EditText mEditText, String beforeload) {
this.webView = webView;
this.edittext = mEditText;
this.beforeload = beforeload;
this.waitForBeforeload = beforeload != null;
}
/**
* Override the URL that should be loaded
*
* Legacy (deprecated in API 24)
* For Android 6 and below.
*
* @param webView
* @param url
*/
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
return shouldOverrideUrlLoading(url, null);
}
/**
* Override the URL that should be loaded
*
* New (added in API 24)
* For Android 7 and above.
*
* @param webView
* @param request
*/
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request) {
return shouldOverrideUrlLoading(request.getUrl().toString(), request.getMethod());
}
/**
@@ -938,17 +1213,55 @@ public class InAppBrowser extends CordovaPlugin {
*
* This handles a small subset of all the URIs that would be encountered.
*
* @param webView
* @param url
* @param method
*/
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
public boolean shouldOverrideUrlLoading(String url, String method) {
boolean override = false;
boolean useBeforeload = false;
String errorMessage = null;
if (beforeload.equals("yes") && method == null) {
useBeforeload = true;
} else if(beforeload.equals("yes")
//TODO handle POST requests then this condition can be removed:
&& !method.equals("POST"))
{
useBeforeload = true;
} else if(beforeload.equals("get") && (method == null || method.equals("GET"))) {
useBeforeload = true;
} else if(beforeload.equals("post") && (method == null || method.equals("POST"))) {
//TODO handle POST requests
errorMessage = "beforeload doesn't yet support POST requests";
}
// On first URL change, initiate JS callback. Only after the beforeload event, continue.
if (useBeforeload && this.waitForBeforeload) {
if(sendBeforeLoad(url, method)) {
return true;
}
}
if(errorMessage != null) {
try {
LOG.e(LOG_TAG, errorMessage);
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", url);
obj.put("code", -1);
obj.put("message", errorMessage);
sendUpdate(obj, true, PluginResult.Status.ERROR);
} catch(Exception e) {
LOG.e(LOG_TAG, "Error sending loaderror for " + url + ": " + e.toString());
}
}
if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
override = true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
@@ -957,7 +1270,7 @@ public class InAppBrowser extends CordovaPlugin {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
override = true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
@@ -988,15 +1301,89 @@ public class InAppBrowser extends CordovaPlugin {
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
return true;
override = true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
// Test for whitelisted custom scheme names like mycoolapp:// or twitteroauthresponse:// (Twitter Oauth Response)
else if (!url.startsWith("http:") && !url.startsWith("https:") && url.matches("^[A-Za-z0-9+.-]*://.*?$")) {
if (allowedSchemes == null) {
String allowed = preferences.getString("AllowedSchemes", null);
if(allowed != null) {
allowedSchemes = allowed.split(",");
}
}
if (allowedSchemes != null) {
for (String scheme : allowedSchemes) {
if (url.startsWith(scheme)) {
try {
JSONObject obj = new JSONObject();
obj.put("type", "customscheme");
obj.put("url", url);
sendUpdate(obj, true);
override = true;
} catch (JSONException ex) {
LOG.e(LOG_TAG, "Custom Scheme URI passed in has caused a JSON error.");
}
}
}
}
}
if (useBeforeload) {
this.waitForBeforeload = true;
}
return override;
}
private boolean sendBeforeLoad(String url, String method) {
try {
JSONObject obj = new JSONObject();
obj.put("type", BEFORELOAD);
obj.put("url", url);
if(method != null) {
obj.put("method", method);
}
sendUpdate(obj, true);
return true;
} catch (JSONException ex) {
LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
}
return false;
}
/**
* Legacy (deprecated in API 21)
* For Android 4.4 and below.
* @param view
* @param url
* @return
*/
@SuppressWarnings("deprecation")
@Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
return shouldInterceptRequest(url, super.shouldInterceptRequest(view, url), null);
}
/**
* New (added in API 21)
* For Android 5.0 and above.
*
* @param webView
* @param request
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
return shouldInterceptRequest(request.getUrl().toString(), super.shouldInterceptRequest(view, request), request.getMethod());
}
public WebResourceResponse shouldInterceptRequest(String url, WebResourceResponse response, String method) {
return response;
}
/*
* onPageStarted fires the LOAD_START_EVENT
*
@@ -1022,7 +1409,7 @@ public class InAppBrowser extends CordovaPlugin {
// Update the UI if we haven't already
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
}
try {
JSONObject obj = new JSONObject();
@@ -1034,11 +1421,14 @@ public class InAppBrowser extends CordovaPlugin {
}
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// Set the namespace for postMessage()
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
injectDeferredObject("window.webkit={messageHandlers:{cordova_iab:cordova_iab}}", null);
}
// CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush();
@@ -1046,6 +1436,10 @@ public class InAppBrowser extends CordovaPlugin {
CookieSyncManager.getInstance().sync();
}
// https://issues.apache.org/jira/browse/CB-11248
view.clearFocus();
view.requestFocus();
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
@@ -1073,6 +1467,46 @@ public class InAppBrowser extends CordovaPlugin {
}
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", error.getUrl());
obj.put("code", 0);
obj.put("sslerror", error.getPrimaryError());
String message;
switch (error.getPrimaryError()) {
case SslError.SSL_DATE_INVALID:
message = "The date of the certificate is invalid";
break;
case SslError.SSL_EXPIRED:
message = "The certificate has expired";
break;
case SslError.SSL_IDMISMATCH:
message = "Hostname mismatch";
break;
default:
case SslError.SSL_INVALID:
message = "A generic error occurred";
break;
case SslError.SSL_NOTYETVALID:
message = "The certificate is not yet valid";
break;
case SslError.SSL_UNTRUSTED:
message = "The certificate authority is not trusted";
break;
}
obj.put("message", message);
sendUpdate(obj, true, PluginResult.Status.ERROR);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
handler.cancel();
}
/**
* On received http auth request.
*/

View File

@@ -104,7 +104,7 @@ public class InAppChromeClient extends WebChromeClient {
if(defaultValue.startsWith("gap-iab://")) {
PluginResult scriptResult;
String scriptCallbackId = defaultValue.substring(10);
if (scriptCallbackId.startsWith("InAppBrowser")) {
if (scriptCallbackId.matches("^InAppBrowser[0-9]{1,10}$")) {
if(message == null || message.length() == 0) {
scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray());
} else {
@@ -118,9 +118,14 @@ public class InAppChromeClient extends WebChromeClient {
result.confirm("");
return true;
}
else {
// Anything else that doesn't look like InAppBrowser0123456789 should end up here
LOG.w(LOG_TAG, "InAppBrowser callback called with invalid callbackId : "+ scriptCallbackId);
result.cancel();
return true;
}
}
else
{
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();

View File

@@ -1,43 +0,0 @@
<!---
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.
-->
# 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

View File

@@ -1,24 +0,0 @@
<!---
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.
-->
# BlackBerry 10-In-App-Browser-Plugin
Die Funktionalität ist im app-Browser vollständig in gemeinsamen Js enthalten. Es gibt keine native Implementierung benötigt. Um dieses Plugin zu installieren, folgen Sie dem [Command-Line Interface Guide](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface).
Wenn Sie nicht die Cordova-Befehlszeilenschnittstelle verwenden, folgen Sie [Verwenden Plugman zu Plugins verwalten](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

View File

@@ -1,24 +0,0 @@
<!---
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.
-->
# BlackBerry 10 In-App-Browser Plugin
El en el navegador de aplicación funcionalidad está enteramente dentro de js común. No hay ninguna aplicación nativa necesaria. Para instalar este plugin, siga la [Guía de la interfaz de línea de comandos](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface).
Si no utiliza la interfaz de línea de comandos de Cordova, siga [Usando Plugman para gestionar 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

View File

@@ -1,24 +0,0 @@
<!---
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.
-->
# BlackBerry 10 In-App-Browser Plugin
Le dans le navigateur de l'application, la fonctionnalité est entièrement contenue dans js commun. Il n'y a aucune implémentation native requise. Pour installer ce plugin, suivez le [Guide de l'Interface de ligne de commande](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface).
Si vous n'utilisez pas l'Interface de ligne de commande de Cordova, suivez [Les Plugman à l'aide à gérer les 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

View File

@@ -1,24 +0,0 @@
<!---
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.
-->
# BlackBerry 10 In-App-Browser Plugin
Il browser app funzionalità è interamente contenuta nel comune js. Non esiste alcuna implementazione nativa richiesto. Per installare questo plugin, seguire la [Guida per l'interfaccia della riga di comando](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface).
Se non si utilizza l'interfaccia della riga di comando di Cordova, seguire [Utilizzando Plugman per gestire i plugin](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

View File

@@ -1,24 +0,0 @@
<!---
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.
-->
# BlackBerry 10 In-App-Browser Plugin
アプリケーション ブラウザーの機能は全く一般的な js に含まれています。 ネイティブ実装する必要はありません。 このプラグインをインストールするには[コマンド ライン インターフェイス ガイド](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface).
コルドバのコマンド ライン インターフェイスを使用していない場合は場合、[管理のプラグインを使用して Plugman](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

View File

@@ -1,24 +0,0 @@
<!---
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.
-->
# 블랙베리 10 애플 리 케이 션-브라우저 플러그인
응용 프로그램 브라우저에서 기능은 완전히 포함 된 일반적인 js. 필요 없는 기본 구현이입니다. 이 플러그인을 설치 하려면 [명령줄 인터페이스 가이드](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface) 를 따라합니다.
코르도바 명령줄 인터페이스를 사용 하지 않는 경우 [관리 플러그인을 사용 하 여 Plugman](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

View File

@@ -1,24 +0,0 @@
<!---
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.
-->
# BlackBerry 10 In-App-Browser Plugin
W aplikacji Przeglądarka funkcjonalność jest całkowicie zawarty w wspólnej js. Tam jest nie native wdrażania wymagane. Aby zainstalować ten plugin, następować po ten [Przewodnik interfejsu wiersza polecenia](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface).
Jeśli nie używasz interfejsu wiersza polecenia Cordova, następować po [Przy użyciu Plugman do zarządzania wtyczki](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

View File

@@ -1,24 +0,0 @@
<!---
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.
-->
# 黑莓 10 的應用程式瀏覽器外掛程式
在應用程式瀏覽器功能完全包含在常見的 js。 還有沒有本機的實施所需。 若要安裝此外掛程式,請按照[命令列介面指南](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface).
如果你不使用的科爾多瓦命令列介面,請按照[使用 Plugman 管理外掛程式](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

View File

@@ -29,27 +29,43 @@ var browserWrap,
forwardButton,
closeButton;
function attachNavigationEvents(element, callback) {
function attachNavigationEvents (element, callback) {
var onError = function () {
callback({ type: "loaderror", url: this.contentWindow.location}, {keepCallback: true});
try {
callback({ type: 'loaderror', url: this.contentWindow.location.href }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
} catch (err) {
// blocked by CORS :\
callback({ type: 'loaderror', url: null }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
}
};
element.addEventListener("pageshow", function () {
callback({ type: "loadstart", url: this.contentWindow.location}, {keepCallback: true});
element.addEventListener('pageshow', function () {
try {
callback({ type: 'loadstart', url: this.contentWindow.location.href }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
} catch (err) {
// blocked by CORS :\
callback({ type: 'loadstart', url: null }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
}
});
element.addEventListener("load", function () {
callback({ type: "loadstop", url: this.contentWindow.location}, {keepCallback: true});
element.addEventListener('load', function () {
try {
callback({ type: 'loadstop', url: this.contentWindow.location.href }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
} catch (err) {
// blocked by CORS :\
callback({ type: 'loadstop', url: null }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
}
});
element.addEventListener("error", onError);
element.addEventListener("abort", onError);
element.addEventListener('error', onError);
element.addEventListener('abort', onError);
}
var IAB = {
close: function (win, lose) {
if (browserWrap) {
if (win) win({ type: "exit" });
// use the "open" function callback so that the exit event is fired properly
if (IAB._win) IAB._win({ type: 'exit' });
browserWrap.parentNode.removeChild(browserWrap);
browserWrap = null;
@@ -59,109 +75,108 @@ var IAB = {
show: function (win, lose) {
if (browserWrap) {
browserWrap.style.display = "block";
browserWrap.style.display = 'block';
}
},
open: function (win, lose, args) {
var strUrl = args[0],
target = args[1],
features = args[2];
var strUrl = args[0];
var target = args[1];
var features = args[2];
if (target === "_self" || !target) {
IAB._win = win;
if (target === '_self' || !target) {
window.location = strUrl;
} else if (target === "_system") {
modulemapper.getOriginalSymbol(window, 'window.open').call(window, strUrl, "_blank");
} else if (target === '_system') {
modulemapper.getOriginalSymbol(window, 'window.open').call(window, strUrl, '_blank');
} else {
// "_blank" or anything else
if (!browserWrap) {
browserWrap = document.createElement("div");
browserWrap.style.position = "absolute";
browserWrap.style.top = "0";
browserWrap.style.left = "0";
browserWrap.style.boxSizing = "border-box";
browserWrap.style.borderWidth = "40px";
browserWrap.style.width = "100vw";
browserWrap.style.height = "100vh";
browserWrap.style.borderStyle = "solid";
browserWrap.style.borderColor = "rgba(0,0,0,0.25)";
browserWrap = document.createElement('div');
browserWrap.style.position = 'absolute';
browserWrap.style.top = '0';
browserWrap.style.left = '0';
browserWrap.style.boxSizing = 'border-box';
browserWrap.style.borderWidth = '40px';
browserWrap.style.width = '100vw';
browserWrap.style.height = '100vh';
browserWrap.style.borderStyle = 'solid';
browserWrap.style.borderColor = 'rgba(0,0,0,0.25)';
browserWrap.onclick = function () {
setTimeout(function () {
IAB.close(win);
IAB.close();
}, 0);
};
document.body.appendChild(browserWrap);
}
if (features.indexOf("hidden=yes") !== -1) {
browserWrap.style.display = "none";
if (features.indexOf('hidden=yes') !== -1) {
browserWrap.style.display = 'none';
}
popup = document.createElement("iframe");
popup.style.borderWidth = "0px";
popup.style.width = "100%";
popup = document.createElement('iframe');
popup.style.borderWidth = '0px';
popup.style.width = '100%';
browserWrap.appendChild(popup);
if (features.indexOf("location=yes") !== -1 || features.indexOf("location") === -1) {
popup.style.height = "calc(100% - 60px)";
popup.style.marginBottom = "-4px";
if (features.indexOf('location=yes') !== -1 || features.indexOf('location') === -1) {
popup.style.height = 'calc(100% - 60px)';
popup.style.marginBottom = '-4px';
navigationButtonsDiv = document.createElement("div");
navigationButtonsDiv.style.height = "60px";
navigationButtonsDiv.style.backgroundColor = "#404040";
navigationButtonsDiv.style.zIndex = "999";
navigationButtonsDiv = document.createElement('div');
navigationButtonsDiv.style.height = '60px';
navigationButtonsDiv.style.backgroundColor = '#404040';
navigationButtonsDiv.style.zIndex = '999';
navigationButtonsDiv.onclick = function (e) {
e.cancelBubble = true;
};
navigationButtonsDivInner = document.createElement("div");
navigationButtonsDivInner.style.paddingTop = "10px";
navigationButtonsDivInner.style.height = "50px";
navigationButtonsDivInner.style.width = "160px";
navigationButtonsDivInner.style.margin = "0 auto";
navigationButtonsDivInner.style.backgroundColor = "#404040";
navigationButtonsDivInner.style.zIndex = "999";
navigationButtonsDivInner = document.createElement('div');
navigationButtonsDivInner.style.paddingTop = '10px';
navigationButtonsDivInner.style.height = '50px';
navigationButtonsDivInner.style.width = '160px';
navigationButtonsDivInner.style.margin = '0 auto';
navigationButtonsDivInner.style.backgroundColor = '#404040';
navigationButtonsDivInner.style.zIndex = '999';
navigationButtonsDivInner.onclick = function (e) {
e.cancelBubble = true;
};
backButton = document.createElement('button');
backButton.style.width = '40px';
backButton.style.height = '40px';
backButton.style.borderRadius = '40px';
backButton = document.createElement("button");
backButton.style.width = "40px";
backButton.style.height = "40px";
backButton.style.borderRadius = "40px";
backButton.innerHTML = "←";
backButton.addEventListener("click", function (e) {
if (popup.canGoBack)
popup.goBack();
backButton.innerHTML = '←';
backButton.addEventListener('click', function (e) {
if (popup.canGoBack) { popup.goBack(); }
});
forwardButton = document.createElement("button");
forwardButton.style.marginLeft = "20px";
forwardButton.style.width = "40px";
forwardButton.style.height = "40px";
forwardButton.style.borderRadius = "40px";
forwardButton = document.createElement('button');
forwardButton.style.marginLeft = '20px';
forwardButton.style.width = '40px';
forwardButton.style.height = '40px';
forwardButton.style.borderRadius = '40px';
forwardButton.innerHTML = "→";
forwardButton.addEventListener("click", function (e) {
if (popup.canGoForward)
popup.goForward();
forwardButton.innerHTML = '→';
forwardButton.addEventListener('click', function (e) {
if (popup.canGoForward) { popup.goForward(); }
});
closeButton = document.createElement("button");
closeButton.style.marginLeft = "20px";
closeButton.style.width = "40px";
closeButton.style.height = "40px";
closeButton.style.borderRadius = "40px";
closeButton = document.createElement('button');
closeButton.style.marginLeft = '20px';
closeButton.style.width = '40px';
closeButton.style.height = '40px';
closeButton.style.borderRadius = '40px';
closeButton.innerHTML = "✖";
closeButton.addEventListener("click", function (e) {
closeButton.innerHTML = '✖';
closeButton.addEventListener('click', function (e) {
setTimeout(function () {
IAB.close(win);
IAB.close();
}, 0);
});
@@ -176,7 +191,7 @@ var IAB = {
browserWrap.appendChild(navigationButtonsDiv);
} else {
popup.style.height = "100%";
popup.style.height = '100%';
}
// start listening for navigation events
@@ -187,8 +202,8 @@ var IAB = {
},
injectScriptCode: function (win, fail, args) {
var code = args[0],
hasCallback = args[1];
var code = args[0];
var hasCallback = args[1];
if (browserWrap && popup) {
try {
@@ -196,7 +211,7 @@ var IAB = {
if (hasCallback) {
win([]);
}
} catch(e) {
} catch (e) {
console.error('Error occured while trying to injectScriptCode: ' + JSON.stringify(e));
}
}
@@ -208,7 +223,7 @@ var IAB = {
if (fail) {
fail(msg);
}
},
},
injectStyleCode: function (win, fail, args) {
var msg = 'Browser cordova-plugin-inappbrowser injectStyleCode is not yet implemented';
@@ -229,4 +244,4 @@ var IAB = {
module.exports = IAB;
require("cordova/exec/proxy").add("InAppBrowser", module.exports);
require('cordova/exec/proxy').add('InAppBrowser', module.exports);

View File

@@ -1,191 +0,0 @@
/*
*
* 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.
*
*/
// https://developer.mozilla.org/en-US/docs/WebAPI/Browser
var modulemapper = require('cordova/modulemapper');
var origOpenFunc = modulemapper.getOriginalSymbol(window, 'window.open');
var browserWrap;
var IABExecs = {
close: function (win, lose) {
if (browserWrap) {
browserWrap.parentNode.removeChild(browserWrap);
browserWrap = null;
if (typeof(win) == "function") win({type:'exit'});
}
},
/*
* Reveal browser if opened hidden
*/
show: function (win, lose) {
console.error('[FirefoxOS] show not implemented');
},
hide: function (win, lose) {
console.error('[FirefoxOS] hide not implemented');
},
open: function (win, lose, args) {
var strUrl = args[0],
target = args[1],
features_string = args[2] || "location=yes", //location=yes is default
features = {};
var features_list = features_string.split(',');
features_list.forEach(function(feature) {
var tup = feature.split('=');
if (tup[1] == 'yes') {
tup[1] = true;
} else if (tup[1] == 'no') {
tup[1] = false;
} else {
var number = parseInt(tup[1]);
if (!isNaN(number)) {
tup[1] = number;
}
}
features[tup[0]] = tup[1];
});
function updateIframeSizeNoLocation() {
browserWrap.style.width = window.innerWidth + 'px';
browserWrap.style.height = window.innerHeight + 'px';
browserWrap.style.zIndex = '999999999';
browserWrap.browser.style.height = (window.innerHeight - 60) + 'px';
browserWrap.browser.style.width = browserWrap.style.width;
}
if (target === '_system') {
origOpenFunc.apply(window, [strUrl, '_blank']);
} else if (target === '_blank') {
var browserElem = document.createElement('iframe');
browserElem.setAttribute('mozbrowser', true);
// make this loaded in its own child process
browserElem.setAttribute('remote', true);
browserElem.setAttribute('src', strUrl);
if (browserWrap) {
document.body.removeChild(browserWrap);
}
browserWrap = document.createElement('div');
// assign browser element to browserWrap for future reference
browserWrap.browser = browserElem;
browserWrap.classList.add('inAppBrowserWrap');
// position fixed so that it works even when page is scrolled
browserWrap.style.position = 'fixed';
browserElem.style.position = 'absolute';
browserElem.style.border = 0;
browserElem.style.top = '60px';
browserElem.style.left = '0px';
updateIframeSizeNoLocation();
var menu = document.createElement('menu');
menu.setAttribute('type', 'toolbar');
var close = document.createElement('li');
var back = document.createElement('li');
var forward = document.createElement('li');
close.appendChild(document.createTextNode('×'));
back.appendChild(document.createTextNode('<'));
forward.appendChild(document.createTextNode('>'));
close.classList.add('inAppBrowserClose');
back.classList.add('inAppBrowserBack');
forward.classList.add('inAppBrowserForward');
var checkForwardBackward = function () {
var backReq = browserElem.getCanGoBack();
backReq.onsuccess = function() {
if (this.result) {
back.classList.remove('disabled');
} else {
back.classList.add('disabled');
}
};
var forwardReq = browserElem.getCanGoForward();
forwardReq.onsuccess = function() {
if (this.result) {
forward.classList.remove('disabled');
} else {
forward.classList.add('disabled');
}
};
};
browserElem.addEventListener('mozbrowserloadend', checkForwardBackward);
close.addEventListener('click', function () {
setTimeout(function () {
IABExecs.close(win, lose);
}, 0);
}, false);
back.addEventListener('click', function () {
browserElem.goBack();
}, false);
forward.addEventListener('click', function () {
browserElem.goForward();
}, false);
menu.appendChild(back);
menu.appendChild(forward);
menu.appendChild(close);
browserWrap.appendChild(menu);
browserWrap.appendChild(browserElem);
document.body.appendChild(browserWrap);
//we use mozbrowserlocationchange instead of mozbrowserloadstart to get the url
browserElem.addEventListener('mozbrowserlocationchange', function(e){
win({
type:'loadstart',
url : e.detail
});
}, false);
browserElem.addEventListener('mozbrowserloadend', function(e){
win({type:'loadstop'});
}, false);
browserElem.addEventListener('mozbrowsererror', function(e){
win({type:'loaderror'});
}, false);
browserElem.addEventListener('mozbrowserclose', function(e){
win({type:'exit'});
}, false);
} else {
window.location = strUrl;
}
},
injectScriptCode: function (code, bCB) {
console.error('[FirefoxOS] injectScriptCode not implemented');
},
injectScriptFile: function (file, bCB) {
console.error('[FirefoxOS] injectScriptFile not implemented');
}
};
module.exports = IABExecs;
require('cordova/exec/proxy').add('InAppBrowser', module.exports);

View File

@@ -1,113 +0,0 @@
/*
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>
#ifdef __CORDOVA_4_0_0
#import <Cordova/CDVUIWebViewDelegate.h>
#else
#import <Cordova/CDVWebViewDelegate.h>
#endif
@class CDVInAppBrowserViewController;
@interface CDVInAppBrowser : CDVPlugin {
}
@property (nonatomic, retain) CDVInAppBrowserViewController* inAppBrowserViewController;
@property (nonatomic, copy) NSString* callbackId;
@property (nonatomic, copy) NSRegularExpression *callbackIdPattern;
- (void)open:(CDVInvokedUrlCommand*)command;
- (void)close:(CDVInvokedUrlCommand*)command;
- (void)injectScriptCode:(CDVInvokedUrlCommand*)command;
- (void)show:(CDVInvokedUrlCommand*)command;
- (void)hide:(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, assign) BOOL clearcache;
@property (nonatomic, assign) BOOL clearsessioncache;
@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, CDVScreenOrientationDelegate>{
@private
NSString* _userAgent;
NSString* _prevUserAgent;
NSInteger _userAgentLockToken;
CDVInAppBrowserOptions *_browserOptions;
#ifdef __CORDOVA_4_0_0
CDVUIWebViewDelegate* _webViewDelegate;
#else
CDVWebViewDelegate* _webViewDelegate;
#endif
}
@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
@interface CDVInAppBrowserNavigationController : UINavigationController
@property (nonatomic, weak) id <CDVScreenOrientationDelegate> orientationDelegate;
@end

View File

@@ -0,0 +1,27 @@
/*
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/CDVScreenOrientationDelegate.h>
@interface CDVInAppBrowserNavigationController : UINavigationController
@property (nonatomic, weak) id <CDVScreenOrientationDelegate> orientationDelegate;
@end

View File

@@ -0,0 +1,63 @@
/*
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 "CDVInAppBrowserNavigationController.h"
@implementation CDVInAppBrowserNavigationController : UINavigationController
- (void) dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion {
if ( self.presentedViewController) {
[super dismissViewControllerAnimated:flag completion:completion];
}
}
- (void) viewDidLoad {
[super viewDidLoad];
}
- (CGRect) invertFrameIfNeeded:(CGRect)rect {
if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
CGFloat temp = rect.size.width;
rect.size.width = rect.size.height;
rect.size.height = temp;
}
rect.origin = CGPointZero;
return rect;
}
#pragma mark CDVScreenOrientationDelegate
- (BOOL)shouldAutorotate
{
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(shouldAutorotate)]) {
return [self.orientationDelegate shouldAutorotate];
}
return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(supportedInterfaceOrientations)]) {
return [self.orientationDelegate supportedInterfaceOrientations];
}
return 1 << UIInterfaceOrientationPortrait;
}
@end

View File

@@ -0,0 +1,50 @@
/*
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.
*/
@interface CDVInAppBrowserOptions : NSObject {}
@property (nonatomic, assign) BOOL location;
@property (nonatomic, assign) BOOL toolbar;
@property (nonatomic, copy) NSString* closebuttoncaption;
@property (nonatomic, copy) NSString* closebuttoncolor;
@property (nonatomic, assign) BOOL lefttoright;
@property (nonatomic, copy) NSString* toolbarposition;
@property (nonatomic, copy) NSString* toolbarcolor;
@property (nonatomic, assign) BOOL toolbartranslucent;
@property (nonatomic, assign) BOOL hidenavigationbuttons;
@property (nonatomic, copy) NSString* navigationbuttoncolor;
@property (nonatomic, assign) BOOL cleardata;
@property (nonatomic, assign) BOOL clearcache;
@property (nonatomic, assign) BOOL clearsessioncache;
@property (nonatomic, assign) BOOL hidespinner;
@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 hidden;
@property (nonatomic, assign) BOOL disallowoverscroll;
@property (nonatomic, copy) NSString* beforeload;
+ (CDVInAppBrowserOptions*)parseOptions:(NSString*)options;
@end

View File

@@ -0,0 +1,90 @@
/*
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 "CDVInAppBrowserOptions.h"
@implementation CDVInAppBrowserOptions
- (id)init
{
if (self = [super init]) {
// default values
self.location = YES;
self.toolbar = YES;
self.closebuttoncaption = nil;
self.toolbarposition = @"bottom";
self.cleardata = NO;
self.clearcache = NO;
self.clearsessioncache = NO;
self.hidespinner = NO;
self.enableviewportscale = NO;
self.mediaplaybackrequiresuseraction = NO;
self.allowinlinemediaplayback = NO;
self.hidden = NO;
self.disallowoverscroll = NO;
self.hidenavigationbuttons = NO;
self.closebuttoncolor = nil;
self.lefttoright = false;
self.toolbarcolor = nil;
self.toolbartranslucent = YES;
self.beforeload = @"";
}
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

View File

@@ -0,0 +1,80 @@
/*
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 "CDVWKInAppBrowserUIDelegate.h"
#import "CDVInAppBrowserOptions.h"
#import "CDVInAppBrowserNavigationController.h"
@class CDVWKInAppBrowserViewController;
@interface CDVWKInAppBrowser : CDVPlugin {
UIWindow * tmpWindow;
@private
NSString* _beforeload;
BOOL _waitForBeforeload;
}
@property (nonatomic, retain) CDVWKInAppBrowser* instance;
@property (nonatomic, retain) CDVWKInAppBrowserViewController* inAppBrowserViewController;
@property (nonatomic, copy) NSString* callbackId;
@property (nonatomic, copy) NSRegularExpression *callbackIdPattern;
+ (id) getInstance;
- (void)open:(CDVInvokedUrlCommand*)command;
- (void)close:(CDVInvokedUrlCommand*)command;
- (void)injectScriptCode:(CDVInvokedUrlCommand*)command;
- (void)show:(CDVInvokedUrlCommand*)command;
- (void)hide:(CDVInvokedUrlCommand*)command;
- (void)loadAfterBeforeload:(CDVInvokedUrlCommand*)command;
@end
@interface CDVWKInAppBrowserViewController : UIViewController <CDVScreenOrientationDelegate,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>{
@private
CDVInAppBrowserOptions *_browserOptions;
NSDictionary *_settings;
}
@property (nonatomic, strong) IBOutlet WKWebView* webView;
@property (nonatomic, strong) IBOutlet WKWebViewConfiguration* configuration;
@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, strong) IBOutlet CDVWKInAppBrowserUIDelegate* webViewUIDelegate;
@property (nonatomic, weak) id <CDVScreenOrientationDelegate> orientationDelegate;
@property (nonatomic, weak) CDVWKInAppBrowser* 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 : (NSString*) colorString : (int) buttonIndex;
- (id)initWithBrowserOptions: (CDVInAppBrowserOptions*) browserOptions andSettings:(NSDictionary*) settings;
@end

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
/*
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 <WebKit/WebKit.h>
@interface CDVWKInAppBrowserUIDelegate : NSObject <WKUIDelegate>{
@private
UIViewController* _viewController;
}
@property (nonatomic, copy) NSString* title;
- (instancetype)initWithTitle:(NSString*)title;
-(void) setViewController:(UIViewController*) viewController;
@end

View File

@@ -0,0 +1,127 @@
/*
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 "CDVWKInAppBrowserUIDelegate.h"
@implementation CDVWKInAppBrowserUIDelegate
- (instancetype)initWithTitle:(NSString*)title
{
self = [super init];
if (self) {
self.title = title;
}
return self;
}
- (void) webView:(WKWebView*)webView runJavaScriptAlertPanelWithMessage:(NSString*)message
initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void (^)(void))completionHandler
{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:self.title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction* action)
{
completionHandler();
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:ok];
[[self getViewController] presentViewController:alert animated:YES completion:nil];
}
- (void) webView:(WKWebView*)webView runJavaScriptConfirmPanelWithMessage:(NSString*)message
initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void (^)(BOOL result))completionHandler
{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:self.title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction* action)
{
completionHandler(YES);
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:ok];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction* action)
{
completionHandler(NO);
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:cancel];
[[self getViewController] presentViewController:alert animated:YES completion:nil];
}
- (void) webView:(WKWebView*)webView runJavaScriptTextInputPanelWithPrompt:(NSString*)prompt
defaultText:(NSString*)defaultText initiatedByFrame:(WKFrameInfo*)frame
completionHandler:(void (^)(NSString* result))completionHandler
{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:self.title
message:prompt
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction* action)
{
completionHandler(((UITextField*)alert.textFields[0]).text);
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:ok];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction* action)
{
completionHandler(nil);
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:cancel];
[alert addTextFieldWithConfigurationHandler:^(UITextField* textField) {
textField.text = defaultText;
}];
[[self getViewController] presentViewController:alert animated:YES completion:nil];
}
-(UIViewController*) getViewController
{
return _viewController;
}
-(void) setViewController:(UIViewController*) viewController
{
_viewController = viewController;
}
@end

View File

@@ -1,92 +0,0 @@
/*
*
* 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 Ubuntu.Components.Popups 0.1
import Ubuntu.Components 0.1
import com.canonical.Oxide 1.0
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])
}
}
}
}
property string usContext: "oxide://main-world/2"
function executeJS(scId, code) {
var req = _view.rootFrame.sendMessage(usContext, "EXECUTE", {code: code});
req.onreply = function(response) {
var code = 'cordova.callback(' + scId + ', JSON.parse(\'' + JSON.stringify(response.result) + '\'))';
console.warn(code);
cordova.javaScriptExecNeeded(code);
console.warn("RESP:" + JSON.stringify(response));
};
}
WebView {
width: parent.width
y: urlEntry.height
height: parent.height - y
url: url1
id: _view
onLoadingStateChanged: {
root.exec("InAppBrowser", "loadFinished", [_view.loading])
}
context: WebContext {
id: webcontext
userScripts: [
UserScript {
context: usContext
emulateGreasemonkey: true
url: "InAppBrowser_escapeScript.js"
}
]
}
}
}

View File

@@ -1,32 +0,0 @@
/*
*
* 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.
*
*/
/* jshint -W061 */
/* global oxide */
oxide.addMessageHandler("EXECUTE", function(msg) {
var code = msg.args.code;
try {
msg.reply({result: eval(code)});
} catch(e) {
msg.error("Code threw exception: \"" + e + "\"");
}
});

Binary file not shown.

Before

Width:  |  Height:  |  Size: 461 B

View File

@@ -1,109 +0,0 @@
/*
*
* 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; \
function createObject() { \
component = Qt.createComponent(%1); \
if (component.status == Component.Ready) \
finishCreation(); \
else \
component.statusChanged.connect(finishCreation); \
} \
function finishCreation() { \
CordovaWrapper.global.inappbrowser = component.createObject(root, \
{root: root, cordova: cordova, url1: %2}); \
} \
createObject()";
const char EXIT_EVENT[] = "{type: 'exit'}";
const char LOADSTART_EVENT[] = "{type: 'loadstart'}";
const char LOADSTOP_EVENT[] = "{type: 'loadstop'}";
const char LOADERROR_EVENT[] = "{type: 'loaderror'}";
void Inappbrowser::open(int cb, int, const QString &url, const QString &, const QString &) {
assert(_eventCb == 0);
_eventCb = cb;
QString path = m_cordova->get_app_dir() + "/../qml/InAppBrowser.qml";
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.global.inappbrowser.visible = true");
}
void Inappbrowser::hide(int, int) {
m_cordova->execQML("CordovaWrapper.global.inappbrowser.visible = false");
}
void Inappbrowser::close(int, int) {
m_cordova->execQML("CordovaWrapper.global.inappbrowser.destroy()");
this->callbackWithoutRemove(_eventCb, EXIT_EVENT);
_eventCb = 0;
}
void Inappbrowser::injectStyleFile(int scId, int ecId, const QString& src, bool b) {
QString code("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %1; d.head.appendChild(c);})(document)");
code = code.arg(CordovaInternal::format(src));
injectScriptCode(scId, ecId, code, b);
}
void Inappbrowser::injectStyleCode(int scId, int ecId, const QString& src, bool b) {
QString code("(function(d) { var c = d.createElement('style'); c.innerHTML = %1; d.body.appendChild(c); })(document)");
code = code.arg(CordovaInternal::format(src));
injectScriptCode(scId, ecId, code, b);
}
void Inappbrowser::injectScriptFile(int scId, int ecId, const QString& src, bool b) {
QString code("(function(d) { var c = d.createElement('script'); c.src = %1; d.body.appendChild(c);})(document)");
code = code.arg(CordovaInternal::format(src));
injectScriptCode(scId, ecId, code, b);
}
void Inappbrowser::injectScriptCode(int scId, int, const QString& code, bool) {
m_cordova->execQML(QString("CordovaWrapper.global.inappbrowser.executeJS(%2, %1)").arg(CordovaInternal::format(code)).arg(scId));
}
void Inappbrowser::loadFinished(bool status) {
if (!status) {
this->callbackWithoutRemove(_eventCb, LOADSTOP_EVENT);
} else {
this->callbackWithoutRemove(_eventCb, LOADSTART_EVENT);
}
}

View File

@@ -1,62 +0,0 @@
/*
*
* 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 hide(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(bool status);
private:
int _eventCb;
};
#endif

View File

@@ -1,4 +1,4 @@
/*
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -21,9 +21,10 @@
/* jslint sloppy:true */
/* global Windows:true, setImmediate */
/* eslint standard/no-callback-literal : 0 */
var cordova = require('cordova'),
urlutil = require('cordova/urlutil');
var cordova = require('cordova');
var urlutil = require('cordova/urlutil');
var browserWrap,
popup,
@@ -40,56 +41,56 @@ var browserWrap,
// http://msdn.microsoft.com/en-us/library/windows/apps/dn301831.aspx
var isWebViewAvailable = cordova.platformId === 'windows';
function attachNavigationEvents(element, callback) {
function attachNavigationEvents (element, callback) {
if (isWebViewAvailable) {
element.addEventListener("MSWebViewNavigationStarting", function (e) {
callback({ type: "loadstart", url: e.uri}, {keepCallback: true} );
element.addEventListener('MSWebViewNavigationStarting', function (e) {
callback({ type: 'loadstart', url: e.uri }, {keepCallback: true});
});
element.addEventListener("MSWebViewNavigationCompleted", function (e) {
element.addEventListener('MSWebViewNavigationCompleted', function (e) {
if (e.isSuccess) {
callback({ type: "loadstop", url: e.uri }, { keepCallback: true });
callback({ type: 'loadstop', url: e.uri }, { keepCallback: true });
} else {
callback({ type: "loaderror", url: e.uri, code: e.webErrorStatus, message: "Navigation failed with error code " + e.webErrorStatus}, { keepCallback: true });
callback({ type: 'loaderror', url: e.uri, code: e.webErrorStatus, message: 'Navigation failed with error code ' + e.webErrorStatus }, { keepCallback: true });
}
});
element.addEventListener("MSWebViewUnviewableContentIdentified", function (e) {
element.addEventListener('MSWebViewUnviewableContentIdentified', function (e) {
// WebView found the content to be not HTML.
// http://msdn.microsoft.com/en-us/library/windows/apps/dn609716.aspx
callback({ type: "loaderror", url: e.uri, code: e.webErrorStatus, message: "Navigation failed with error code " + e.webErrorStatus}, { keepCallback: true });
callback({ type: 'loaderror', url: e.uri, code: e.webErrorStatus, message: 'Navigation failed with error code ' + e.webErrorStatus }, { keepCallback: true });
});
element.addEventListener("MSWebViewContentLoading", function (e) {
element.addEventListener('MSWebViewContentLoading', function (e) {
if (navigationButtonsDiv && popup) {
if (popup.canGoBack) {
backButton.removeAttribute("disabled");
backButton.removeAttribute('disabled');
} else {
backButton.setAttribute("disabled", "true");
backButton.setAttribute('disabled', 'true');
}
if (popup.canGoForward) {
forwardButton.removeAttribute("disabled");
forwardButton.removeAttribute('disabled');
} else {
forwardButton.setAttribute("disabled", "true");
forwardButton.setAttribute('disabled', 'true');
}
}
});
} else {
var onError = function () {
callback({ type: "loaderror", url: this.contentWindow.location}, {keepCallback: true});
callback({ type: 'loaderror', url: this.contentWindow.location }, {keepCallback: true});
};
element.addEventListener("unload", function () {
callback({ type: "loadstart", url: this.contentWindow.location}, {keepCallback: true});
element.addEventListener('unload', function () {
callback({ type: 'loadstart', url: this.contentWindow.location }, {keepCallback: true});
});
element.addEventListener("load", function () {
callback({ type: "loadstop", url: this.contentWindow.location}, {keepCallback: true});
element.addEventListener('load', function () {
callback({ type: 'loadstop', url: this.contentWindow.location }, {keepCallback: true});
});
element.addEventListener("error", onError);
element.addEventListener("abort", onError);
element.addEventListener('error', onError);
element.addEventListener('abort', onError);
}
}
@@ -98,7 +99,7 @@ var IAB = {
setImmediate(function () {
if (browserWrap) {
if (navigationEventsCallback) {
navigationEventsCallback({ type: "exit" });
navigationEventsCallback({ type: 'exit' });
}
browserWrap.parentNode.removeChild(browserWrap);
@@ -107,52 +108,52 @@ var IAB = {
browserWrap = null;
popup = null;
document.removeEventListener("backbutton", hardwareBackCallback, false);
document.removeEventListener('backbutton', hardwareBackCallback, false);
}
});
},
show: function (win, lose) {
setImmediate(function () {
if (browserWrap) {
browserWrap.style.display = "block";
browserWrap.style.display = 'block';
}
});
},
hide: function (win, lose) {
if (browserWrap) {
browserWrap.style.display = "none";
browserWrap.style.display = 'none';
}
},
open: function (win, lose, args) {
// make function async so that we can add navigation events handlers before view is loaded and navigation occured
setImmediate(function () {
var strUrl = args[0],
target = args[1],
features = args[2],
url;
var strUrl = args[0];
var target = args[1];
var features = args[2];
var url;
navigationEventsCallback = win;
if (target === "_system") {
if (target === '_system') {
url = new Windows.Foundation.Uri(strUrl);
Windows.System.Launcher.launchUriAsync(url);
} else if (target === "_self" || !target) {
} else if (target === '_self' || !target) {
window.location = strUrl;
} else {
// "_blank" or anything else
if (!browserWrap) {
var browserWrapStyle = document.createElement('link');
browserWrapStyle.rel = "stylesheet";
browserWrapStyle.type = "text/css";
browserWrapStyle.href = urlutil.makeAbsolute("/www/css/inappbrowser.css");
browserWrapStyle.rel = 'stylesheet';
browserWrapStyle.type = 'text/css';
browserWrapStyle.href = urlutil.makeAbsolute('/www/css/inappbrowser.css');
document.head.appendChild(browserWrapStyle);
browserWrap = document.createElement("div");
browserWrap.className = "inAppBrowserWrap";
browserWrap = document.createElement('div');
browserWrap.className = 'inAppBrowserWrap';
if (features.indexOf("fullscreen=yes") > -1) {
browserWrap.classList.add("inAppBrowserWrapFullscreen");
if (features.indexOf('fullscreen=yes') > -1) {
browserWrap.classList.add('inAppBrowserWrapFullscreen');
}
// Save body overflow style to be able to reset it back later
@@ -166,22 +167,22 @@ var IAB = {
document.body.appendChild(browserWrap);
// Hide scrollbars for the whole body while inappbrowser's window is open
document.body.style.msOverflowStyle = "none";
document.body.style.msOverflowStyle = 'none';
}
if (features.indexOf("hidden=yes") !== -1) {
browserWrap.style.display = "none";
if (features.indexOf('hidden=yes') !== -1) {
browserWrap.style.display = 'none';
}
popup = document.createElement(isWebViewAvailable ? "x-ms-webview" : "iframe");
if (popup instanceof HTMLIFrameElement) {
popup = document.createElement(isWebViewAvailable ? 'x-ms-webview' : 'iframe');
if (popup instanceof HTMLIFrameElement) { // eslint-disable-line no-undef
// For iframe we need to override bacground color of parent element here
// otherwise pages without background color set will have transparent background
popup.style.backgroundColor = "white";
popup.style.backgroundColor = 'white';
}
popup.style.borderWidth = "0px";
popup.style.width = "100%";
popup.style.marginBottom = "-5px";
popup.style.borderWidth = '0px';
popup.style.width = '100%';
popup.style.marginBottom = '-5px';
browserWrap.appendChild(popup);
@@ -191,14 +192,14 @@ var IAB = {
}, 0);
};
if (features.indexOf("hardwareback=yes") > -1 || features.indexOf("hardwareback") === -1) {
if (features.indexOf('hardwareback=yes') > -1 || features.indexOf('hardwareback') === -1) {
hardwareBackCallback = function () {
if (browserWrap.style.display === 'none') {
// NOTE: backbutton handlers have to throw an exception in order to prevent
// returning 'true' inside cordova-js, which would mean that the event is handled by user.
// Throwing an exception means that the default/system navigation behavior will take place,
// which is to exit the app if the navigation stack is empty.
throw 'Exit the app';
throw 'Exit the app'; // eslint-disable-line no-throw-literal
}
if (popup.canGoBack) {
@@ -207,59 +208,57 @@ var IAB = {
closeHandler();
}
};
} else if (features.indexOf("hardwareback=no") > -1) {
} else if (features.indexOf('hardwareback=no') > -1) {
hardwareBackCallback = function () {
if (browserWrap.style.display === 'none') {
// See comment above
throw 'Exit the app';
throw 'Exit the app'; // eslint-disable-line no-throw-literal
}
closeHandler();
};
}
document.addEventListener("backbutton", hardwareBackCallback, false);
document.addEventListener('backbutton', hardwareBackCallback, false);
if (features.indexOf("location=yes") !== -1 || features.indexOf("location") === -1) {
popup.style.height = "calc(100% - 70px)";
if (features.indexOf('location=yes') !== -1 || features.indexOf('location') === -1) {
popup.style.height = 'calc(100% - 70px)';
navigationButtonsDiv = document.createElement("div");
navigationButtonsDiv.className = "inappbrowser-app-bar";
navigationButtonsDiv = document.createElement('div');
navigationButtonsDiv.className = 'inappbrowser-app-bar';
navigationButtonsDiv.onclick = function (e) {
e.cancelBubble = true;
};
navigationButtonsDivInner = document.createElement("div");
navigationButtonsDivInner.className = "inappbrowser-app-bar-inner";
navigationButtonsDivInner = document.createElement('div');
navigationButtonsDivInner.className = 'inappbrowser-app-bar-inner';
navigationButtonsDivInner.onclick = function (e) {
e.cancelBubble = true;
};
backButton = document.createElement("div");
backButton.innerText = "back";
backButton.className = "app-bar-action action-back";
backButton.addEventListener("click", function (e) {
if (popup.canGoBack)
popup.goBack();
backButton = document.createElement('div');
backButton.innerText = 'back';
backButton.className = 'app-bar-action action-back';
backButton.addEventListener('click', function (e) {
if (popup.canGoBack) { popup.goBack(); }
});
forwardButton = document.createElement("div");
forwardButton.innerText = "forward";
forwardButton.className = "app-bar-action action-forward";
forwardButton.addEventListener("click", function (e) {
if (popup.canGoForward)
popup.goForward();
forwardButton = document.createElement('div');
forwardButton.innerText = 'forward';
forwardButton.className = 'app-bar-action action-forward';
forwardButton.addEventListener('click', function (e) {
if (popup.canGoForward) { popup.goForward(); }
});
closeButton = document.createElement("div");
closeButton.innerText = "close";
closeButton.className = "app-bar-action action-close";
closeButton.addEventListener("click", closeHandler);
closeButton = document.createElement('div');
closeButton.innerText = 'close';
closeButton.className = 'app-bar-action action-close';
closeButton.addEventListener('click', closeHandler);
if (!isWebViewAvailable) {
// iframe navigation is not yet supported
backButton.setAttribute("disabled", "true");
forwardButton.setAttribute("disabled", "true");
backButton.setAttribute('disabled', 'true');
forwardButton.setAttribute('disabled', 'true');
}
navigationButtonsDivInner.appendChild(backButton);
@@ -269,14 +268,14 @@ var IAB = {
browserWrap.appendChild(navigationButtonsDiv);
} else {
popup.style.height = "100%";
popup.style.height = '100%';
}
// start listening for navigation events
attachNavigationEvents(popup, navigationEventsCallback);
if (isWebViewAvailable) {
strUrl = strUrl.replace("ms-appx://", "ms-appx-web://");
strUrl = strUrl.replace('ms-appx://', 'ms-appx-web://');
}
popup.src = strUrl;
}
@@ -285,11 +284,11 @@ var IAB = {
injectScriptCode: function (win, fail, args) {
setImmediate(function () {
var code = args[0],
hasCallback = args[1];
var code = args[0];
var hasCallback = args[1];
if (isWebViewAvailable && browserWrap && popup) {
var op = popup.invokeScriptAsync("eval", code);
var op = popup.invokeScriptAsync('eval', code);
op.oncomplete = function (e) {
if (hasCallback) {
// return null if event target is unavailable by some reason
@@ -305,10 +304,10 @@ var IAB = {
injectScriptFile: function (win, fail, args) {
setImmediate(function () {
var filePath = args[0],
hasCallback = args[1];
var filePath = args[0];
var hasCallback = args[1];
if (!!filePath) {
if (filePath) {
filePath = urlutil.makeAbsolute(filePath);
}
@@ -317,8 +316,8 @@ var IAB = {
var uri = new Windows.Foundation.Uri(filePath.replace('ms-appx-web:', 'ms-appx:'));
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).done(function (file) {
Windows.Storage.FileIO.readTextAsync(file).done(function (code) {
var op = popup.invokeScriptAsync("eval", code);
op.oncomplete = function(e) {
var op = popup.invokeScriptAsync('eval', code);
op.oncomplete = function (e) {
if (hasCallback) {
var result = [e.target.result];
win(result);
@@ -334,8 +333,8 @@ var IAB = {
injectStyleCode: function (win, fail, args) {
setImmediate(function () {
var code = args[0],
hasCallback = args[1];
var code = args[0];
var hasCallback = args[1];
if (isWebViewAvailable && browserWrap && popup) {
injectCSS(popup, code, hasCallback && win);
@@ -345,8 +344,8 @@ var IAB = {
injectStyleFile: function (win, fail, args) {
setImmediate(function () {
var filePath = args[0],
hasCallback = args[1];
var filePath = args[0];
var hasCallback = args[1];
filePath = filePath && urlutil.makeAbsolute(filePath);
@@ -368,11 +367,11 @@ var IAB = {
function injectCSS (webView, cssCode, callback) {
// This will automatically escape all thing that we need (quotes, slashes, etc.)
var escapedCode = JSON.stringify(cssCode);
var evalWrapper = "(function(d){var c=d.createElement('style');c.innerHTML=%s;d.head.appendChild(c);})(document)"
var evalWrapper = '(function(d){var c=d.createElement(\'style\');c.innerHTML=%s;d.head.appendChild(c);})(document)'
.replace('%s', escapedCode);
var op = webView.invokeScriptAsync("eval", evalWrapper);
op.oncomplete = function() {
var op = webView.invokeScriptAsync('eval', evalWrapper);
op.oncomplete = function () {
if (callback) {
callback([]);
}
@@ -383,4 +382,4 @@ function injectCSS (webView, cssCode, callback) {
module.exports = IAB;
require("cordova/exec/proxy").add("InAppBrowser", module.exports);
require('cordova/exec/proxy').add('InAppBrowser', module.exports);

View File

@@ -1,530 +0,0 @@
/*
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 hide(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
if (browser != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
browser.Visibility = Visibility.Collapsed;
AppBar.IsVisible = false;
});
}
}
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);
}
}
}
}

2
tests/.eslintrc.yml Normal file
View File

@@ -0,0 +1,2 @@
env:
jasmine: true

14
tests/package.json Normal file
View File

@@ -0,0 +1,14 @@
{
"name": "cordova-plugin-inappbrowser-tests",
"version": "4.0.0",
"description": "",
"cordova": {
"id": "cordova-plugin-inappbrowser-tests",
"platforms": []
},
"keywords": [
"ecosystem:cordova"
],
"author": "",
"license": "Apache-2.0"
}

View File

@@ -20,7 +20,7 @@
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="cordova-plugin-inappbrowser-tests"
version="1.6.2-dev">
version="4.0.0">
<name>Cordova InAppBrowser Plugin Tests</name>
<license>Apache 2.0</license>
@@ -29,5 +29,12 @@
<js-module src="tests.js" name="tests">
</js-module>
<platform name="ios">
<!-- The WKWebView implementation for inappbrowser requires the presence of this plugin -->
<dependency id="cordova-plugin-wkwebview-engine" />
<dependency id="cordova-plugin-wkwebview-engine-allowfileaccess" url="https://github.com/knight9999/cordova-plugin-wkwebview-engine-allowfileaccess.git" />
</platform>
<asset src="resources" target="cdvtests/iab-resources" />
</plugin>

View File

@@ -16,5 +16,5 @@
* specific language governing permissions and limitations
* under the License.
*/
var d = document.getElementById("header");
d.innerHTML = "Script file successfully injected";
var d = document.getElementById('header');
d.innerHTML = 'Script file successfully injected';

View File

@@ -19,11 +19,13 @@
*
*/
/* jshint jasmine: true */
/* global MSApp */
var cordova = require('cordova');
var isWindows = cordova.platformId == 'windows';
var isWindows = cordova.platformId === 'windows';
var isIos = cordova.platformId === 'ios';
var isAndroid = cordova.platformId === 'android';
var isBrowser = cordova.platformId === 'browser';
window.alert = window.alert || navigator.notification.alert;
if (isWindows && navigator && navigator.notification && navigator.notification.alert) {
@@ -32,126 +34,171 @@ if (isWindows && navigator && navigator.notification && navigator.notification.a
}
exports.defineAutoTests = function () {
var createTests = function (platformOpts) {
platformOpts = platformOpts || '';
describe('cordova.InAppBrowser', function () {
describe('cordova.InAppBrowser', function () {
it("inappbrowser.spec.1 should exist", function () {
expect(cordova.InAppBrowser).toBeDefined();
it('inappbrowser.spec.1 should exist', function () {
expect(cordova.InAppBrowser).toBeDefined();
});
it('inappbrowser.spec.2 should contain open function', function () {
expect(cordova.InAppBrowser.open).toBeDefined();
expect(cordova.InAppBrowser.open).toEqual(jasmine.any(Function));
});
});
it("inappbrowser.spec.2 should contain open function", function () {
expect(cordova.InAppBrowser.open).toBeDefined();
expect(cordova.InAppBrowser.open).toEqual(jasmine.any(Function));
});
});
describe('open method', function () {
describe('open method', function () {
if (cordova.platformId === 'osx') {
pending('Open method not fully supported on OSX.');
return;
}
if (cordova.platformId == 'osx') {
pending('Open method not fully supported on OSX.');
return;
}
var iabInstance;
var originalTimeout;
var url = 'https://dist.apache.org/repos/dist/dev/cordova/';
var badUrl = 'http://bad-uri/';
var iabInstance;
var originalTimeout;
var url = 'https://dist.apache.org/repos/dist/dev/cordova/';
var badUrl = 'http://bad-uri/';
beforeEach(function () {
beforeEach(function () {
// increase timeout to ensure test url could be loaded within test time
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
iabInstance = null;
});
iabInstance = null;
});
afterEach(function (done) {
afterEach(function (done) {
// restore original timeout
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
if (iabInstance !== null && iabInstance.close) {
iabInstance.close();
if (iabInstance !== null && iabInstance.close) {
iabInstance.close();
}
iabInstance = null;
// add some extra time so that iab dialog is closed
setTimeout(done, 2000);
});
function verifyEvent (evt, type) {
expect(evt).toBeDefined();
expect(evt.type).toEqual(type);
// `exit` event does not have url field, browser returns null url for CORS requests
if (type !== 'exit' && !isBrowser) {
expect(evt.url).toEqual(url);
}
}
iabInstance = null;
// add some extra time so that iab dialog is closed
setTimeout(done, 2000);
});
function verifyEvent(evt, type) {
expect(evt).toBeDefined();
expect(evt.type).toEqual(type);
if (type !== 'exit') { // `exit` event does not have url field
expect(evt.url).toEqual(url);
function verifyLoadErrorEvent (evt) {
expect(evt).toBeDefined();
expect(evt.type).toEqual('loaderror');
expect(evt.url).toEqual(badUrl);
expect(evt.code).toEqual(jasmine.any(Number));
expect(evt.message).toEqual(jasmine.any(String));
}
}
function verifyLoadErrorEvent(evt) {
expect(evt).toBeDefined();
expect(evt.type).toEqual('loaderror');
expect(evt.url).toEqual(badUrl);
expect(evt.code).toEqual(jasmine.any(Number));
expect(evt.message).toEqual(jasmine.any(String));
}
it('inappbrowser.spec.3 should return InAppBrowser instance with required methods', function () {
iabInstance = cordova.InAppBrowser.open(url, '_blank', platformOpts);
it("inappbrowser.spec.3 should retun InAppBrowser instance with required methods", function () {
iabInstance = cordova.InAppBrowser.open(url, '_blank');
expect(iabInstance).toBeDefined();
expect(iabInstance).toBeDefined();
expect(iabInstance.addEventListener).toEqual(jasmine.any(Function));
expect(iabInstance.removeEventListener).toEqual(jasmine.any(Function));
expect(iabInstance.close).toEqual(jasmine.any(Function));
expect(iabInstance.show).toEqual(jasmine.any(Function));
expect(iabInstance.hide).toEqual(jasmine.any(Function));
expect(iabInstance.executeScript).toEqual(jasmine.any(Function));
expect(iabInstance.insertCSS).toEqual(jasmine.any(Function));
});
it("inappbrowser.spec.4 should support loadstart and loadstop events", function (done) {
var onLoadStart = jasmine.createSpy('loadstart event callback').and.callFake(function (evt) {
verifyEvent(evt, 'loadstart');
expect(iabInstance.addEventListener).toEqual(jasmine.any(Function));
expect(iabInstance.removeEventListener).toEqual(jasmine.any(Function));
expect(iabInstance.close).toEqual(jasmine.any(Function));
expect(iabInstance.show).toEqual(jasmine.any(Function));
expect(iabInstance.hide).toEqual(jasmine.any(Function));
expect(iabInstance.executeScript).toEqual(jasmine.any(Function));
expect(iabInstance.insertCSS).toEqual(jasmine.any(Function));
});
iabInstance = cordova.InAppBrowser.open(url, '_blank');
iabInstance.addEventListener('loadstart', onLoadStart);
iabInstance.addEventListener('loadstop', function (evt) {
verifyEvent(evt, 'loadstop');
expect(onLoadStart).toHaveBeenCalled();
done();
});
});
it('inappbrowser.spec.4 should support loadstart and loadstop events', function (done) {
var onLoadStart = jasmine.createSpy('loadstart event callback').and.callFake(function (evt) {
verifyEvent(evt, 'loadstart');
});
it("inappbrowser.spec.5 should support exit event", function (done) {
iabInstance = cordova.InAppBrowser.open(url, '_blank');
iabInstance.addEventListener('exit', function (evt) {
verifyEvent(evt, 'exit');
done();
iabInstance = cordova.InAppBrowser.open(url, '_blank', platformOpts);
iabInstance.addEventListener('loadstart', onLoadStart);
iabInstance.addEventListener('loadstop', function (evt) {
verifyEvent(evt, 'loadstop');
if (!isBrowser) {
// according to documentation, "loadstart" event is not supported on browser
// https://github.com/apache/cordova-plugin-inappbrowser#browser-quirks-1
expect(onLoadStart).toHaveBeenCalled();
}
done();
});
});
iabInstance.close();
iabInstance = null;
});
it("inappbrowser.spec.6 should support loaderror event", function (done) {
iabInstance = cordova.InAppBrowser.open(badUrl, '_blank');
iabInstance.addEventListener('loaderror', function (evt) {
verifyLoadErrorEvent(evt);
done();
it('inappbrowser.spec.5 should support exit event', function (done) {
iabInstance = cordova.InAppBrowser.open(url, '_blank', platformOpts);
iabInstance.addEventListener('exit', function (evt) {
verifyEvent(evt, 'exit');
done();
});
iabInstance.addEventListener('loadstop', function (evt) {
iabInstance.close();
iabInstance = null;
});
});
it('inappbrowser.spec.6 should support loaderror event', function (done) {
if (isBrowser) {
// according to documentation, "loaderror" event is not supported on browser
// https://github.com/apache/cordova-plugin-inappbrowser#browser-quirks-1
pending('Browser platform doesn\'t support loaderror event');
}
iabInstance = cordova.InAppBrowser.open(badUrl, '_blank', platformOpts);
iabInstance.addEventListener('loaderror', function (evt) {
verifyLoadErrorEvent(evt);
done();
});
});
it('inappbrowser.spec.7 should support message event', function (done) {
if (!isAndroid && !isIos) {
return pending(cordova.platformId + ' platform doesn\'t support message event');
}
var messageKey = 'my_message';
var messageValue = 'is_this';
iabInstance = cordova.InAppBrowser.open(url, '_blank', platformOpts);
iabInstance.addEventListener('message', function (evt) {
// Verify message event
expect(evt).toBeDefined();
expect(evt.type).toEqual('message');
expect(evt.data).toBeDefined();
expect(evt.data[messageKey]).toBeDefined();
expect(evt.data[messageKey]).toEqual(messageValue);
done();
});
iabInstance.addEventListener('loadstop', function (evt) {
var code = '(function(){\n' +
' var message = {' + messageKey + ': "' + messageValue + '"};\n' +
' webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(message));\n' +
'})()';
iabInstance.executeScript({ code: code });
});
});
});
});
};
createTests();
};
exports.defineManualTests = function (contentEl, createActionButton) {
function doOpen(url, target, params, numExpectedRedirects, useWindowOpen) {
var platformOpts = '';
var platform_info = '';
function doOpen (url, target, params, numExpectedRedirects, useWindowOpen) {
numExpectedRedirects = numExpectedRedirects || 0;
useWindowOpen = useWindowOpen || false;
console.log("Opening " + url);
console.log('Opening ' + url);
var counts;
var lastLoadStartURL;
var wasReset = false;
function reset() {
function reset () {
counts = {
'loaderror': 0,
'loadstart': 0,
@@ -172,49 +219,51 @@ exports.defineManualTests = function (contentEl, createActionButton) {
if (useWindowOpen) {
console.log('Use window.open() for url');
iab = window.open(url, target, params, callbacks);
}
else {
} else {
if (platformOpts) {
params += (params ? ',' : '') + platformOpts;
}
iab = cordova.InAppBrowser.open(url, target, params, callbacks);
}
if (!iab) {
alert('open returned ' + iab);
alert('open returned ' + iab); // eslint-disable-line no-undef
return;
}
function logEvent(e) {
function logEvent (e) {
console.log('IAB event=' + JSON.stringify(e));
counts[e.type]++;
// Verify that event.url gets updated on redirects.
if (e.type == 'loadstart') {
if (e.url == lastLoadStartURL) {
alert('Unexpected: loadstart fired multiple times for the same URL.');
if (e.type === 'loadstart') {
if (e.url === lastLoadStartURL) {
alert('Unexpected: loadstart fired multiple times for the same URL.'); // eslint-disable-line no-undef
}
lastLoadStartURL = e.url;
}
// Verify the right number of loadstart events were fired.
if (e.type == 'loadstop' || e.type == 'loaderror') {
if (e.url != lastLoadStartURL) {
alert('Unexpected: ' + e.type + ' event.url != loadstart\'s event.url');
if (e.type === 'loadstop' || e.type === 'loaderror') {
if (e.url !== lastLoadStartURL) {
alert('Unexpected: ' + e.type + ' event.url != loadstart\'s event.url'); // eslint-disable-line no-undef
}
if (numExpectedRedirects === 0 && counts.loadstart !== 1) {
// Do allow a loaderror without a loadstart (e.g. in the case of an invalid URL).
if (!(e.type == 'loaderror' && counts.loadstart === 0)) {
alert('Unexpected: got multiple loadstart events. (' + counts.loadstart + ')');
if (!(e.type === 'loaderror' && counts.loadstart === 0)) {
alert('Unexpected: got multiple loadstart events. (' + counts.loadstart + ')'); // eslint-disable-line no-undef
}
} else if (numExpectedRedirects > 0 && counts.loadstart < (numExpectedRedirects + 1)) {
alert('Unexpected: should have got at least ' + (numExpectedRedirects + 1) + ' loadstart events, but got ' + counts.loadstart);
alert('Unexpected: should have got at least ' + (numExpectedRedirects + 1) + ' loadstart events, but got ' + counts.loadstart); // eslint-disable-line no-undef
}
wasReset = true;
numExpectedRedirects = 0;
reset();
}
// Verify that loadend / loaderror was called.
if (e.type == 'exit') {
if (e.type === 'exit') {
var numStopEvents = counts.loadstop + counts.loaderror;
if (numStopEvents === 0 && !wasReset) {
alert('Unexpected: browser closed without a loadstop or loaderror.');
alert('Unexpected: browser closed without a loadstop or loaderror.'); // eslint-disable-line no-undef
} else if (numStopEvents > 1) {
alert('Unexpected: got multiple loadstop/loaderror events.');
alert('Unexpected: got multiple loadstop/loaderror events.'); // eslint-disable-line no-undef
}
}
}
@@ -222,33 +271,31 @@ exports.defineManualTests = function (contentEl, createActionButton) {
return iab;
}
function doHookOpen(url, target, params, numExpectedRedirects) {
function doHookOpen (url, target, params, numExpectedRedirects) {
var originalFunc = window.open;
var wasClobbered = window.hasOwnProperty('open');
window.open = cordova.InAppBrowser.open;
try {
doOpen(url, target, params, numExpectedRedirects, true);
}
finally {
} finally {
if (wasClobbered) {
window.open = originalFunc;
}
else {
console.log('just delete, to restore open from prototype');
} else {
console.log('just delete, to restore open from prototype');
delete window.open;
}
}
}
function openWithStyle(url, cssUrl, useCallback) {
function openWithStyle (url, cssUrl, useCallback) {
var iab = doOpen(url, '_blank', 'location=yes');
var callback = function (results) {
if (results && results.length === 0) {
alert('Results verified');
alert('Results verified'); // eslint-disable-line no-undef
} else {
console.log(results);
alert('Got: ' + typeof (results) + '\n' + JSON.stringify(results));
alert('Got: ' + typeof (results) + '\n' + JSON.stringify(results)); // eslint-disable-line no-undef
}
};
if (cssUrl) {
@@ -258,21 +305,21 @@ exports.defineManualTests = function (contentEl, createActionButton) {
} else {
iab.addEventListener('loadstop', function (event) {
iab.insertCSS({ code: '#style-update-literal { \ndisplay: block !important; \n}' },
useCallback && callback);
useCallback && callback);
});
}
}
function openWithScript(url, jsUrl, useCallback) {
function openWithScript (url, jsUrl, useCallback) {
var iab = doOpen(url, '_blank', 'location=yes');
if (jsUrl) {
iab.addEventListener('loadstop', function (event) {
iab.executeScript({ file: jsUrl }, useCallback && function (results) {
if (results && results.length === 0) {
alert('Results verified');
alert('Results verified'); // eslint-disable-line no-undef
} else {
console.log(results);
alert('Got: ' + typeof (results) + '\n' + JSON.stringify(results));
alert('Got: ' + typeof (results) + '\n' + JSON.stringify(results)); // eslint-disable-line no-undef
}
});
});
@@ -285,33 +332,36 @@ exports.defineManualTests = function (contentEl, createActionButton) {
'})()';
iab.executeScript({ code: code }, useCallback && function (results) {
if (results && results.length === 1 && results[0] === 'abc') {
alert('Results verified');
alert('Results verified'); // eslint-disable-line no-undef
} else {
console.log(results);
alert('Got: ' + typeof (results) + '\n' + JSON.stringify(results));
alert('Got: ' + typeof (results) + '\n' + JSON.stringify(results)); // eslint-disable-line no-undef
}
});
});
}
}
var hiddenwnd = null;
var loadlistener = function (event) { alert('background window loaded '); };
function openHidden(url, startHidden) {
var loadlistener = function (event) { alert('background window loaded '); }; // eslint-disable-line no-undef
function openHidden (url, startHidden) {
var shopt = (startHidden) ? 'hidden=yes' : '';
if (platformOpts) {
shopt += (shopt ? ',' : '') + platformOpts;
}
hiddenwnd = cordova.InAppBrowser.open(url, 'random_string', shopt);
if (!hiddenwnd) {
alert('cordova.InAppBrowser.open returned ' + hiddenwnd);
alert('cordova.InAppBrowser.open returned ' + hiddenwnd); // eslint-disable-line no-undef
return;
}
if (startHidden) hiddenwnd.addEventListener('loadstop', loadlistener);
}
function showHidden() {
if (!!hiddenwnd) {
function showHidden () {
if (hiddenwnd) {
hiddenwnd.show();
}
}
function closeHidden() {
if (!!hiddenwnd) {
function closeHidden () {
if (hiddenwnd) {
hiddenwnd.removeEventListener('loadstop', loadlistener);
hiddenwnd.close();
hiddenwnd = null;
@@ -456,34 +506,34 @@ exports.defineManualTests = function (contentEl, createActionButton) {
'<p/> <div id="openHardwareBackYes"></div>' +
'Expected result: hardwareback=yes pressing back button should navigate backwards in history then close InAppBrowser' +
'<p/> <div id="openHardwareBackNo"></div>' +
'Expected result: hardwareback=no pressing back button should close InAppBrowser regardless history' +
'Expected result: hardwareback=no pressing back button should close InAppBrowser regardless history' +
'<p/> <div id="openHardwareBackDefaultAfterNo"></div>' +
'Expected result: consistently open browsers with with the appropriate option: hardwareback=defaults to yes then hardwareback=no then hardwareback=defaults to yes. By default hardwareback is yes so pressing back button should navigate backwards in history then close InAppBrowser';
// CB-7490 We need to wrap this code due to Windows security restrictions
// see http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences for details
if (window.MSApp && window.MSApp.execUnsafeLocalFunction) {
MSApp.execUnsafeLocalFunction(function() {
contentEl.innerHTML = info_div + local_tests + white_listed_tests + non_white_listed_tests + page_with_redirects_tests + pdf_url_tests + invalid_url_tests +
MSApp.execUnsafeLocalFunction(function () {
contentEl.innerHTML = info_div + platform_info + local_tests + white_listed_tests + non_white_listed_tests + page_with_redirects_tests + pdf_url_tests + invalid_url_tests +
css_js_injection_tests + open_hidden_tests + clearing_cache_tests + video_tag_tests + local_with_anchor_tag_tests + hardwareback_tests;
});
} else {
contentEl.innerHTML = info_div + local_tests + white_listed_tests + non_white_listed_tests + page_with_redirects_tests + pdf_url_tests + invalid_url_tests +
contentEl.innerHTML = info_div + platform_info + local_tests + white_listed_tests + non_white_listed_tests + page_with_redirects_tests + pdf_url_tests + invalid_url_tests +
css_js_injection_tests + open_hidden_tests + clearing_cache_tests + video_tag_tests + local_with_anchor_tag_tests + hardwareback_tests;
}
document.getElementById("user-agent").textContent = navigator.userAgent;
document.getElementById('user-agent').textContent = navigator.userAgent;
// we are already in cdvtests directory
var basePath = 'iab-resources/';
var localhtml = basePath + 'local.html',
localpdf = basePath + 'local.pdf',
injecthtml = basePath + 'inject.html',
injectjs = isWindows ? basePath + 'inject.js' : 'inject.js',
injectcss = isWindows ? basePath + 'inject.css' : 'inject.css',
videohtml = basePath + 'video.html';
var localhtml = basePath + 'local.html';
var localpdf = basePath + 'local.pdf';
var injecthtml = basePath + 'inject.html';
var injectjs = isWindows ? basePath + 'inject.js' : 'inject.js';
var injectcss = isWindows ? basePath + 'inject.css' : 'inject.css';
var videohtml = basePath + 'video.html';
//Local
// Local
createActionButton('target=Default', function () {
doOpen(localhtml);
}, 'openLocal');
@@ -512,7 +562,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
doOpen(localhtml, 'random_string', 'toolbarposition=top,location=no');
}, 'openLocalRandomToolBarTopNoLocation');
//White Listed
// White Listed
createActionButton('* target=Default', function () {
doOpen('http://cordova.apache.org');
}, 'openWhiteListed');
@@ -535,7 +585,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
doOpen('http://cordova.apache.org', 'random_string', 'location=no');
}, 'openWhiteListedRandomNoLocation');
//Non White Listed
// Non White Listed
createActionButton('target=Default', function () {
doOpen('http://www.apple.com');
}, 'openNonWhiteListed');
@@ -558,7 +608,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
doOpen('http://www.apple.com', 'random_string', 'location=no');
}, 'openNonWhiteListedRandomNoLocation');
//Page with redirect
// Page with redirect
createActionButton('http://google.co.uk', function () {
doOpen('http://google.co.uk', 'random_string', '', 1);
}, 'openRedirect301');
@@ -566,7 +616,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
doOpen('http://goo.gl/pUFqg', 'random_string', '', 2);
}, 'openRedirect302');
//PDF URL
// PDF URL
createActionButton('Remote URL', function () {
doOpen('http://www.stluciadance.com/prospectus_file/sample.pdf');
}, 'openPDF');
@@ -574,7 +624,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
doOpen(localpdf, '_blank');
}, 'openPDFBlank');
//Invalid URL
// Invalid URL
createActionButton('Invalid Scheme', function () {
doOpen('x-ttp://www.invalid.com/', '_blank');
}, 'openInvalidScheme');
@@ -585,7 +635,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
doOpen('nonexistent.html', '_blank');
}, 'openInvalidMissing');
//CSS / JS injection
// CSS / JS injection
createActionButton('Original Document', function () {
doOpen(injecthtml, '_blank');
}, 'openOriginalDocument');
@@ -614,7 +664,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
openWithScript(injecthtml, null, true);
}, 'openScriptLiteralInjectionCallback');
//Open hidden
// Open hidden
createActionButton('Create Hidden', function () {
openHidden('https://www.google.co.uk', true);
}, 'openHidden');
@@ -634,7 +684,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
}, 2000);
}, 'openVisibleAndHide');
//Clearing cache
// Clearing cache
createActionButton('Clear Browser Cache', function () {
doOpen('https://www.google.co.uk', '_blank', 'clearcache=yes');
}, 'openClearCache');
@@ -642,7 +692,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
doOpen('https://www.google.co.uk', '_blank', 'clearsessioncache=yes');
}, 'openClearSessionCache');
//Video tag
// Video tag
createActionButton('Remote Video', function () {
doOpen(videohtml, '_blank');
}, 'openRemoteVideo');
@@ -653,7 +703,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
doOpen(videohtml, '_blank', 'mediaPlaybackRequiresUserAction=yes');
}, 'openRemoteNeedUserYesVideo');
//Local With Anchor Tag
// Local With Anchor Tag
createActionButton('Anchor1', function () {
doOpen(localhtml + '#bogusanchor', '_blank');
}, 'openAnchor1');
@@ -671,18 +721,18 @@ exports.defineManualTests = function (contentEl, createActionButton) {
createActionButton('hardwareback=no', function () {
doOpen('http://cordova.apache.org', '_blank', 'hardwareback=no');
}, 'openHardwareBackNo');
createActionButton('no hardwareback -> hardwareback=no -> no hardwareback', function() {
var ref = cordova.InAppBrowser.open('https://google.com', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
createActionButton('no hardwareback -> hardwareback=no -> no hardwareback', function () {
var ref = cordova.InAppBrowser.open('https://google.com', '_blank', 'location=yes' + (platformOpts ? ',' + platformOpts : ''));
ref.addEventListener('loadstop', function () {
ref.close();
});
ref.addEventListener('exit', function() {
var ref2 = cordova.InAppBrowser.open('https://google.com', '_blank', 'location=yes,hardwareback=no');
ref2.addEventListener('loadstop', function() {
ref.addEventListener('exit', function () {
var ref2 = cordova.InAppBrowser.open('https://google.com', '_blank', 'location=yes,hardwareback=no' + (platformOpts ? ',' + platformOpts : ''));
ref2.addEventListener('loadstop', function () {
ref2.close();
});
ref2.addEventListener('exit', function() {
cordova.InAppBrowser.open('https://google.com', '_blank', 'location=yes');
ref2.addEventListener('exit', function () {
cordova.InAppBrowser.open('https://google.com', '_blank', 'location=yes' + (platformOpts ? ',' + platformOpts : ''));
});
});
}, 'openHardwareBackDefaultAfterNo');

169
types/index.d.ts vendored
View File

@@ -2,9 +2,11 @@
// Project: https://github.com/apache/cordova-plugin-inappbrowser
// Definitions by: Microsoft Open Technologies Inc <http://msopentech.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
//
//
// Copyright (c) Microsoft Open Technologies Inc
// Licensed under the MIT license.
// TypeScript Version: 2.3
type channel = "loadstart" | "loadstop" | "loaderror" | "exit" | "message" | "customscheme";
interface Window {
/**
@@ -15,34 +17,7 @@ interface Window {
* 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.
*/
open(url: string, target?: "_self", options?: string): InAppBrowser;
/**
* Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
* @param url The URL to load.
* @param target The target in which to load the URL, an optional parameter that defaults to _self.
* @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.
*/
open(url: string, target?: "_blank", options?: string): InAppBrowser;
/**
* Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
* @param url The URL to load.
* @param target The target in which to load the URL, an optional parameter that defaults to _self.
* @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.
*/
open(url: string, target?: "_system", options?: string): InAppBrowser;
/**
* Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
* @param url The URL to load.
* @param target The target in which to load the URL, an optional parameter that defaults to _self.
* @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.
*/
open(url: string, target?: string, options?: string, replace?: boolean): InAppBrowser;
open(url: string, target?: string, options?: string): InAppBrowser;
}
/**
@@ -50,66 +25,28 @@ interface Window {
* NOTE: The InAppBrowser window behaves like a standard web browser, and can't access Cordova APIs.
*/
interface InAppBrowser extends Window {
onloadstart: (type: InAppBrowserEvent) => void;
onloadstop: (type: InAppBrowserEvent) => void;
onloaderror: (type: InAppBrowserEvent) => void;
onexit: (type: InAppBrowserEvent) => void;
onloadstart(type: Event): void;
onloadstop(type: InAppBrowserEvent): void;
onloaderror(type: InAppBrowserEvent): void;
onexit(type: InAppBrowserEvent): void;
// addEventListener overloads
/**
* Adds a listener for an event from the InAppBrowser.
* @param type the event to listen for
* loadstart: event fires when the InAppBrowser starts to load a URL.
* @param type 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.
* @param callback the function that executes when the event fires. The function is
* passed an InAppBrowserEvent object as a parameter.
*/
addEventListener(type: "loadstart", callback: (event: InAppBrowserEvent) => void): void;
addEventListener(type: channel, callback: InAppBrowserEventListenerOrEventListenerObject): void;
/**
* Adds a listener for an event from the InAppBrowser.
* @param type the event to listen for
* 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.
* @param type any custom event that might occur.
* @param callback the function that executes when the event fires. The function is
* passed an InAppBrowserEvent object as a parameter.
*/
addEventListener(type: "loadstop", callback: (event: InAppBrowserEvent) => void): void;
/**
* Adds a listener for an event from the InAppBrowser.
* @param type the event to listen for
* 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.
* @param callback the function that executes when the event fires. The function is
* passed an InAppBrowserEvent object as a parameter.
*/
addEventListener(type: "loaderror", callback: (event: InAppBrowserEvent) => void): void;
/**
* Adds a listener for an event from the InAppBrowser.
* @param type the event to listen for
* 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.
* @param callback the function that executes when the event fires. The function is
* passed an InAppBrowserEvent object as a parameter.
*/
addEventListener(type: "exit", callback: (event: InAppBrowserEvent) => void): void;
/**
* Adds a listener for an event from the InAppBrowser.
* @param type the event to listen for
* 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.
* @param callback the function that executes when the event fires. The function is
* passed an Event object as a parameter.
*/
addEventListener(type: string, callback: (event: Event) => void): void;
addEventListener(type: string, callback: InAppBrowserEventListenerOrEventListenerObject): void;
// removeEventListener overloads
/**
* Removes a listener for an event from the InAppBrowser.
@@ -121,53 +58,11 @@ interface InAppBrowser extends Window {
* @param callback the function that executes when the event fires. The function is
* passed an InAppBrowserEvent object as a parameter.
*/
removeEventListener(type: "loadstart", callback: (event: InAppBrowserEvent) => void): void;
/**
* Removes a listener for an event from the InAppBrowser.
* @param type The event to stop listening for.
* 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.
* @param callback the function that executes when the event fires. The function is
* passed an InAppBrowserEvent object as a parameter.
*/
removeEventListener(type: "loadstop", callback: (event: InAppBrowserEvent) => void): void;
/**
* Removes a listener for an event from the InAppBrowser.
* @param type The event to stop listening for.
* 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.
* @param callback the function that executes when the event fires. The function is
* passed an InAppBrowserEvent object as a parameter.
*/
removeEventListener(type: "loaderror", callback: (event: InAppBrowserEvent) => void): void;
/**
* Removes a listener for an event from the InAppBrowser.
* @param type The event to stop listening for.
* 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.
* @param callback the function that executes when the event fires. The function is
* passed an InAppBrowserEvent object as a parameter.
*/
removeEventListener(type: "exit", callback: (event: InAppBrowserEvent) => void): void;
/**
* Removes a listener for an event from the InAppBrowser.
* @param type The event to stop listening for.
* 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.
* @param callback the function that executes when the event fires. The function is
* passed an Event object as a parameter.
*/
removeEventListener(type: string, callback: (event: Event) => void): void;
removeEventListener(type: channel, callback: InAppBrowserEventListenerOrEventListenerObject): void;
/** Closes the InAppBrowser window. */
close(): void;
/** Hides the InAppBrowser window. Calling this has no effect if the InAppBrowser was already hidden. */
hide(): void;
/**
* Displays an InAppBrowser window that was opened hidden. Calling this has no effect
* if the InAppBrowser was already visible.
@@ -182,29 +77,21 @@ interface InAppBrowser extends Window {
* For multi-line scripts, this is the return value of the last statement,
* or the last expression evaluated.
*/
executeScript(script: { code: string }, callback: (result: any) => void): void;
/**
* Injects JavaScript code into the InAppBrowser window.
* @param script Details of the script to run, specifying either a file or code key.
* @param 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.
*/
executeScript(script: { file: string }, callback: (result: any) => void): void;
executeScript(script: { code: string } | { file: string }, callback: (result: any) => void): void;
/**
* Injects CSS into the InAppBrowser window.
* @param css Details of the script to run, specifying either a file or code key.
* @param callback The function that executes after the CSS is injected.
*/
insertCSS(css: { code: string }, callback: () => void): void;
/**
* Injects CSS into the InAppBrowser window.
* @param css Details of the script to run, specifying either a file or code key.
* @param callback The function that executes after the CSS is injected.
*/
insertCSS(css: { file: string }, callback: () => void): void;
insertCSS(css: { code: string } | { file: string }, callback: () => void): void;
}
type InAppBrowserEventListenerOrEventListenerObject = InAppBrowserEventListener | InAppBrowserEventListenerObject;
type InAppBrowserEventListener = (evt: InAppBrowserEvent) => void;
interface InAppBrowserEventListenerObject {
handleEvent(evt: InAppBrowserEvent): void;
}
interface InAppBrowserEvent extends Event {
@@ -216,4 +103,8 @@ interface InAppBrowserEvent extends Event {
code: number;
/** the error message, only in the case of loaderror. */
message: string;
}
}
interface Cordova {
InAppBrowser: InAppBrowser;
}

View File

@@ -19,75 +19,80 @@
*
*/
(function() {
// special patch to correctly work on Ripple emulator (CB-9760)
if (window.parent && !!window.parent.ripple) { // https://gist.github.com/triceam/4658021
module.exports = window.open.bind(window); // fallback to default window.open behaviour
return;
}
(function () {
var exec = require('cordova/exec');
var channel = require('cordova/channel');
var modulemapper = require('cordova/modulemapper');
var urlutil = require('cordova/urlutil');
function InAppBrowser() {
this.channels = {
function InAppBrowser () {
this.channels = {
'beforeload': channel.create('beforeload'),
'loadstart': channel.create('loadstart'),
'loadstop' : channel.create('loadstop'),
'loaderror' : channel.create('loaderror'),
'exit' : channel.create('exit')
};
'loadstop': channel.create('loadstop'),
'loaderror': channel.create('loaderror'),
'exit': channel.create('exit'),
'customscheme': channel.create('customscheme'),
'message': channel.create('message')
};
}
InAppBrowser.prototype = {
_eventHandler: function (event) {
if (event && (event.type in this.channels)) {
this.channels[event.type].fire(event);
if (event.type === 'beforeload') {
this.channels[event.type].fire(event, this._loadAfterBeforeload);
} else {
this.channels[event.type].fire(event);
}
}
},
_loadAfterBeforeload: function (strUrl) {
strUrl = urlutil.makeAbsolute(strUrl);
exec(null, null, 'InAppBrowser', 'loadAfterBeforeload', [strUrl]);
},
close: function (eventname) {
exec(null, null, "InAppBrowser", "close", []);
exec(null, null, 'InAppBrowser', 'close', []);
},
show: function (eventname) {
exec(null, null, "InAppBrowser", "show", []);
exec(null, null, 'InAppBrowser', 'show', []);
},
hide: function (eventname) {
exec(null, null, "InAppBrowser", "hide", []);
exec(null, null, 'InAppBrowser', 'hide', []);
},
addEventListener: function (eventname,f) {
addEventListener: function (eventname, f) {
if (eventname in this.channels) {
this.channels[eventname].subscribe(f);
}
},
removeEventListener: function(eventname, f) {
removeEventListener: function (eventname, f) {
if (eventname in this.channels) {
this.channels[eventname].unsubscribe(f);
}
},
executeScript: function(injectDetails, cb) {
executeScript: function (injectDetails, cb) {
if (injectDetails.code) {
exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
exec(cb, null, 'InAppBrowser', 'injectScriptCode', [injectDetails.code, !!cb]);
} else if (injectDetails.file) {
exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
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) {
insertCSS: function (injectDetails, cb) {
if (injectDetails.code) {
exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
exec(cb, null, 'InAppBrowser', 'injectStyleCode', [injectDetails.code, !!cb]);
} else if (injectDetails.file) {
exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
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, callbacks) {
module.exports = function (strUrl, strWindowName, strWindowFeatures, 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');
@@ -102,13 +107,13 @@
iab.addEventListener(callbackName, callbacks[callbackName]);
}
var cb = function(eventname) {
iab._eventHandler(eventname);
var cb = function (eventname) {
iab._eventHandler(eventname);
};
strWindowFeatures = strWindowFeatures || "";
strWindowFeatures = strWindowFeatures || '';
exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
exec(cb, cb, 'InAppBrowser', 'open', [strUrl, strWindowName, strWindowFeatures]);
return iab;
};
})();

View File

@@ -1,130 +0,0 @@
/*
*
* 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 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) {
}*/
},
hide: function (win, lose) {
/* empty block, ran out of bacon?
if (browserWrap) {
}*/
},
open: function (win, lose, args) {
var strUrl = args[0],
target = args[1],
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.style.zIndex = "9999999";
browserWrap.onclick = function () {
setTimeout(function () {
IAB.close();
}, 0);
};
document.body.appendChild(browserWrap);
}
var localFile = (strUrl.indexOf('ms-appdata:///') > -1);
if (localFile) {
elem = document.createElement("x-ms-webview");
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";
}
});
} else {
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/exec/proxy").add("InAppBrowser", module.exports);