Compare commits

...

291 Commits

Author SHA1 Message Date
sgrebnov
df94a6c157 CB-10505 Updated version and RELEASENOTES.md for release 1.2.1 2016-02-02 14:29:21 +03:00
Jesse MacFadyen
1f190d517f Merge branch 'master' of https://github.com/uareurapid/cordova-plugin-inappbrowser 2016-02-01 23:13:13 -08:00
sgrebnov
163f7c5a8f Added missing plugin dependency for manual tests 2016-02-01 15:17:55 +03:00
sgrebnov
b024104a54 CB-10451 InAppBrowser: loadstart event is not triggered on Windows
CB-10452 InAppBrowser: 'exit' event is not triggered on Windows
CB-10454 InAppBrowser: 'loaderror' event does not have code and message on Windows
CB-10450 InAppBrowser: Unable to get property 'canGoBack' of undefined on Windows

github close #145
2016-02-01 14:24:55 +03:00
sgrebnov
73ed40fe07 CB-6702 InAppBrowser hangs when opening more than one instance
github close #144
2016-02-01 14:00:52 +03:00
sgrebnov
4d9e4884dd CB-10456 InAppBrowser is not closed if I close it programmatically on Android
guthub close #143
2016-02-01 13:59:42 +03:00
sgrebnov
04c05a5e52 CB-10441 Add auto tests for InAppBrowser plugin
github close #142
2016-02-01 13:58:33 +03:00
sgrebnov
2e0dc26eaa CB-10428 Fix syntax error when browserifying inAppBrowser plugin
github close #141
2016-01-26 16:20:42 +03:00
Joe Bowser
8da5e25eee CB-10407: Re-adding onPageStarted to re-add LOAD_START, even though it's in the wrong place 2016-01-22 14:22:58 -08:00
Steve Gill
15a57485c6 CB-10368 Incremented plugin version. 2016-01-15 16:58:32 -08:00
Steve Gill
c3ccb694d3 CB-10368 Updated version and RELEASENOTES.md for release 1.2.0 2016-01-15 16:35:05 -08:00
Joe Bowser
212e0a34d8 CB-8180: Changing methods of interception in WebViewClient class
This closes #136
2016-01-15 14:11:59 -08:00
Martin Bektchiev
518596a96f Fix lint warnings
This closes #120
2016-01-15 11:45:23 -08:00
sgrebnov
f326121590 CB-10009 Improve InAppBrowser toolbar look and feel on Windows
github close #129
2016-01-11 14:25:11 +03:00
PC Dreams (Paulo Cristo)
fa7c46a316 handle app store urls in system browser 2016-01-05 12:32:47 +00:00
robario
9540f11fcc Using modulemapper 2015-12-18 18:13:01 +09:00
robario
3a1fea5d8b Open a new window on the browser platform
The URL is not supposed to change in the case of SPA.
2015-12-18 17:32:24 +09:00
Shazron Abdullah
2fc2658830 CB-10187 Incremented plugin version. 2015-12-10 16:01:03 -08:00
Shazron Abdullah
ce285e8e06 CB-10187 Updated version and RELEASENOTES.md for release 1.1.1 2015-12-10 16:00:13 -08:00
sgrebnov
65821f907d CB-9445 Improves executeScript callbacks on iOS
This closes #125

Signed-off-by: Shazron Abdullah <shazron@apache.org>
2015-12-10 14:47:43 -08:00
Steve Gill
290ea0ac9c CB-10035 Incremented plugin version. 2015-11-30 17:57:07 -08:00
Shazron Abdullah
542536f790 CB-10040 - re-fix: backwards compatible with cordova-ios < 4.0 2015-11-20 10:53:36 -08:00
Connor Pearson
9b576f303b CB-8534: Allow plugins to respond to onReceivedHttpAuthRequest. This closes #82 2015-11-20 19:59:43 +03:00
Connor Pearson
52cfd3216a CB-3750: Fixes spinner on iOS. This closes #89 2015-11-20 18:40:16 +03:00
Sergey Grebnov
8142c73c84 CB-7696 Document target=_self behavior for Windows
github close #124
2015-11-20 15:22:26 +03:00
Shazron Abdullah
bc9036d90a CB-10040 - Compile Error in InAppBrowser Plugin for iOS - No known instance method for selector 'URLIsWhitelisted:' 2015-11-19 15:22:30 -08:00
Steve Gill
1cd9205eb5 CB-10035 linked issues in RELEASENOTES.md 2015-11-18 22:11:41 -08:00
Steve Gill
5451427c98 CB-10035 Updated version and RELEASENOTES.md for release 1.1.0 2015-11-18 19:45:05 -08:00
Steve Gill
e32b95ccf9 removed r prefix from tags 2015-11-18 15:02:03 -08:00
Jesse MacFadyen
682703aa24 weak ref type was wrong 2015-11-18 14:22:42 -08:00
Steve Gill
6815a48408 CB-10035 Updated RELEASENOTES to be newest to oldest 2015-11-18 13:54:08 -08:00
Jesse MacFadyen
620d92e5c0 Close #91 2015-11-17 23:05:44 -08:00
Jesse MacFadyen
2c002f0f8d Close #85 2015-11-17 15:45:10 -08:00
Jesse MacFadyen
214763c76b Merge branch 'master' of https://github.com/ABB-Austin/cordova-plugin-inappbrowser 2015-11-17 15:07:20 -08:00
Jesse MacFadyen
8fb2244432 Merge branch 'CB-8863' 2015-11-17 13:03:39 -08:00
Jesse MacFadyen
1bc51f9381 fix async self usage 2015-11-17 11:50:40 -08:00
sgrebnov
49757716f5 CB-9150 Fix InAppBrowser executeScript crash on Windows if no data returned 2015-11-17 11:42:55 +03:00
sgrebnov
6b99fb96f8 CB-10008 Fix InAppBrowser popup layout on Windows 2015-11-17 11:17:02 +03:00
Jesse MacFadyen
1912d12697 Merge branch 'fix_status_bar_negative' of https://github.com/vinnyrose/cordova-plugin-inappbrowser 2015-11-16 17:54:08 -08:00
Jesse MacFadyen
5a558344fd Merge branch 'master' of https://github.com/8eo/cordova-plugin-inappbrowser 2015-11-16 17:48:21 -08:00
Jesse MacFadyen
e89f602633 Close #113 2015-11-16 17:46:22 -08:00
Julien Bouquillon
790771bb00 add JIRA issue tracker link 2015-11-16 17:44:40 -08:00
Paul Weber
1afd42aabb CB-9799 Fixed javaDoc errors.. This closes #119 2015-11-10 16:45:00 +03:00
Dmitry Blotsky
32743e0eb9 Actually fixing the contribute link. 2015-10-23 12:11:50 -07:00
Dmitry Blotsky
89c5ee54e7 Fixing contribute link. 2015-10-23 12:03:42 -07:00
sgrebnov
fee0d4e2d8 CB-9760 InAppBrowser: fallback to default window.open behavior on Ripple 2015-10-07 12:03:01 +03:00
Jesse MacFadyen
c08e239143 Close #114 2015-09-14 12:25:59 -07:00
David Weber
2279aee4ff Fix crash on browser window close (https://issues.apache.org/jira/browse/CB-9167) 2015-07-20 13:09:58 +02:00
daserge
368cbcbc41 CB-9378 Fix InAppBrowser not taking whole screen on Windows 2015-07-16 21:35:59 +03:00
Jesse MacFadyen
5c7a9d95a8 remove travis-ci 2015-07-07 17:52:53 -07:00
Anton Antonov
74aa099b7e CB-9158 - InAppBrowser zoomControls are always set to true 2015-06-18 20:28:32 +03:00
Steve Gill
cb1c6b4d24 CB-9192 Incremented plugin version. 2015-06-17 17:35:36 -07:00
Steve Gill
47e332fc92 CB-9202 updated repo url to github mirror in package.json 2015-06-17 14:14:41 -07:00
Steve Gill
3413453d86 CB-9192 Updated version and RELEASENOTES.md for release 1.0.1 2015-06-17 12:36:04 -07:00
Victor Sosa
de9f3e35b4 CB-9128 cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser 2015-06-12 09:41:39 -05:00
Raymond Camden
77d0c99998 fix npm md issue 2015-06-02 10:56:15 -05:00
Steve Gill
ba7cbe58d5 CB-8858 Incremented plugin version. 2015-04-15 16:00:22 -07:00
Steve Gill
7d1b584306 CB-8858 Updated version in package.json for release 1.0.0 2015-04-15 15:50:47 -07:00
Steve Gill
f614dc3193 Revert "CB-8858 Incremented plugin version."
This reverts commit 05fa172116.
2015-04-15 14:31:08 -07:00
Steve Gill
05fa172116 CB-8858 Incremented plugin version. 2015-04-15 13:55:47 -07:00
Steve Gill
aacf70f888 CB-8858 Updated version and RELEASENOTES.md for release 1.0.0 2015-04-15 11:06:38 -07:00
aroberson
8175122c03 Invoke webview if using local file 2015-04-13 15:33:03 -05:00
aroberson
11a2acfd7b Fixed zIndex issue on Windows 8, 8.1 where InAppBrowser opens behind default app. 2015-04-10 08:53:48 -05:00
Steve Gill
ea7e7674f8 CB-8746 gave plugin major version bump 2015-04-09 17:01:06 -07:00
Vladimir Kotikov
e2865db2ea CB-7689 Adds insertCSS support for windows platform 2015-04-07 09:17:09 +03:00
Shazron Abdullah
dfd0999581 CB-4930 - (prefix) InAppBrowser should take into account the status bar 2015-04-03 12:34:11 -07:00
Vladimir Kotikov
461d9e9c4c CB-8635 Improves UX on windows platform
* Adds `fullscreen` option
* Adds ability to apply custom styles to IAB window
2015-04-02 13:32:45 +03:00
Vladimir Kotikov
16353c3466 CB-8661 Return executed script result on Windows 2015-04-02 13:29:00 +03:00
Steve Gill
c85cab15b7 CB-8683 updated wp and browser specific references of old id to new id 2015-04-01 16:34:36 -07:00
Steve Gill
2c1ded2c43 CB-8683 changed plugin-id to pacakge-name 2015-04-01 16:31:51 -07:00
Steve Gill
eb59809c34 CB-8653 properly updated translated docs to use new id 2015-03-31 16:06:01 -07:00
Steve Gill
805d43d61d CB-8653 updated translated docs to use new id 2015-03-31 10:53:32 -07:00
Jesse MacFadyen
9901d62248 Use TRAVIS_BUILD_DIR, install paramedic by npm 2015-03-24 23:34:39 -07:00
Vladimir Kotikov
57f942670c CB-8432 Correct styles for browser wrapper to display it correctly on some pages
* Force z-order for wrapper to show it on top of the whole page
* Apply CSS reset rules to browser wrapper
* Disable parent window scrollbars when browser is shown
2015-03-17 14:18:04 +03:00
Shazron Abdullah
ed1227f61a CB-8659 - Update InAppBrowser to support both cordova-ios 4.0.x and 3.x (closes #93) 2015-03-16 09:42:16 -07:00
daserge
4c8f58d87c CB-7961 Add cordova-plugin-inappbrowser support for browser platform
Added Browser platform support (Chrome, IE, Firefox)
Updated the docs
2015-03-16 13:26:34 +03:00
Steve Gill
1774ceafae CB-8653 Updated Readme 2015-03-13 19:30:44 -07:00
Jesse MacFadyen
00809a3c51 Update docs for Android zoom=no option 2015-03-04 17:49:49 -08:00
Jesse MacFadyen
b96c4a7d9a Merge branch 'master' of https://github.com/jellekralt/cordova-plugin-inappbrowser 2015-03-04 17:42:43 -08:00
Jesse MacFadyen
a45dbc80b4 updated docs, set hardwareback default to true 2015-03-04 00:26:57 -08:00
Jesse MacFadyen
9de15ac8bf Merge branch 'master' of https://github.com/kriserickson/cordova-plugin-inappbrowser 2015-03-04 00:13:29 -08:00
Jesse MacFadyen
f4879e9e50 CB-8570 Integrate TravisCI 2015-03-02 17:21:08 -08:00
Victor Sosa
4a4164c6f6 CB-8438 cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser 2015-02-27 12:51:38 -06:00
Steve Gill
fb8574abde CB-8538 Added package.json file 2015-02-25 00:35:29 -08:00
Maxime Boucher-Allard
f8a80ce27d Keep external android pages in a single tab. (close #61) 2015-02-19 19:56:26 -05:00
Jason Chase
0293771e14 CB-8444 Add a clobber for cordova.InAppBrowser.open (close #80)
- Update doc with workaround for removing clobber
2015-02-19 19:52:05 -05:00
Jason Chase
ad263a1b53 CB-8444 Don't clobber window.open
- Add new symbol/clobber to access open function (`cordova.InAppBrowser.open`)
- Change existing tests to use new symbol (i.e. don't rely on plugin clobber of `window.open`)
- Add tests to use `window.open` via manual replace with new symbol
- Update docs to deprecate plugin clobber of `window.open`
2015-02-12 16:34:32 -05:00
Andrew Grieve
6604d54e12 CB-8429 Incremented plugin version. 2015-02-04 20:54:02 -05:00
Andrew Grieve
90d41e87ce CB-8429 Updated version and RELEASENOTES.md for release 0.6.0 2015-02-04 20:12:45 -05:00
Andrew Grieve
19a2179d1d Add missing license header for src/ubuntu/InAppBrowser_escapeScript.js 2015-02-04 16:03:59 -05:00
Andrew Grieve
bfff56aef4 CB-8270 Remove usage of [arr JSONString], since it's been renamed to cdv_JSONString
Just updating to the new name would make the plugin incompatible with
previous cordova-ios versions.
2015-01-21 11:48:08 -05:00
Maxim Ermilov
e5d6d6f69a ubuntu: implement inject* functions 2014-12-15 16:38:26 +03:00
Maxim Ermilov
88b71b3a57 ubuntu: port to oxide 2014-12-15 16:38:22 +03:00
Ian Clelland
a40a10f1ea Merge branch 'unplug-whitelist' 2014-12-12 07:47:15 -05:00
Mario Rosa
d9900ba783 InAppBrowser, iOS: Setting setStatusBarStyle to -1 causes CGContextSaveGState.
Simple if statement to ensure -1 is not submitted to setStatusBarStyle.
2014-12-05 09:21:01 -05:00
Ian Clelland
514469ab24 CB-7897: Update to work with whilelist plugins in Cordova 4.x 2014-12-03 09:29:22 -05:00
Steve Gill
abbbcc2461 CB-8110 Incremented plugin version. 2014-12-02 16:08:50 -08:00
Steve Gill
b9653af691 CB-8110 Updated version and RELEASENOTES.md for release 0.5.4 2014-12-02 16:07:02 -08:00
Ajitha
2c4bef1f97 Amazon specific changes:
Removed reference to closebuttoncaption according to
https://git-wip-us.apache.org/repos/asf?p=cordova-plugin-inappbrowser.git;a=commit;h=50a78baf22843b0df96ccb4ca83a45bd9ef3fc39
2014-11-22 12:08:22 -08:00
daserge
e785533ab4 CB-7784 Exit event is not fired after InAppBrowser closing 2014-11-12 22:35:10 -08:00
daserge
3056997c78 CB-7697 Add locationBar support to InAppBrowser windows platform version 2014-11-12 22:35:10 -08:00
daserge
3f80b0b59c CB-7690 InAppBrowser loadstart/loadstop events issues
Subscribing to events before navigating
2014-11-12 22:35:10 -08:00
daserge
71b43d39a4 CB-7695 Fix InAppBrowser injectScriptFile for Windows 8.1 / Windows Phone 8.1
Changed injects' paths to include parent folder
Used getFileFromApplicationUriAsync
2014-11-12 22:35:09 -08:00
daserge
d2eaa089f8 CB-7692 InAppBrowser local url opening bug in 8.1
Using ms-appx-web instead of ms-appx
2014-11-12 22:35:09 -08:00
daserge
1bf42c9e3b CB-7688 Alert is not supported in InAppBrowser on Windows platform
Using cordova-plugin-dialogs to enable alerts.
2014-11-12 22:35:09 -08:00
Josh Soref
70d74e5273 CB-7977 Mention deviceready in plugin docs 2014-11-12 12:45:48 -05:00
Josh Soref
2818011249 Dropping trailing whitespace 2014-11-12 12:45:48 -05:00
Ian Clelland
80e4831a7f CB-7897: Update to work with whilelist plugins in Cordova 4.x 2014-10-29 12:09:13 -04:00
Marcel Kinard
7a816d8454 CB-7876 change test target to avoid undesired redirects
The google.com test target would do automatic redirects to geography-specific
domains depending on where the client is, which leads to different behavior
depending where the tester is. This causes confusion, as the test results
may be different in different geographies. Use a test target that doesn't do
that, so the test results are independent of geography.
2014-10-27 12:23:10 -04:00
Marcel Kinard
50a78baf22 CB-7712 remove references to closebuttoncaption
The code for this had been previously commented out, but was still listed in
the docs. So remove it from the docs and remove the dead comments.
2014-10-24 17:45:09 -04:00
Marcel Kinard
216ed8ae57 CB-7850 clarify role of whitelist 2014-10-22 13:07:20 -04:00
Edna Morales
8012ae709b CB-7720 check if event is null since OK string from success callback was removed
github: close #68
2014-10-07 11:37:42 -04:00
Ian Clelland
80010ae309 Merge branch 'master' of https://github.com/sosahvictor/cordova-plugin-inappbrowser 2014-10-06 15:01:13 -04:00
Steven Gill
927e7a8e98 Incremented plugin version. 2014-10-03 17:15:41 -07:00
Steven Gill
003f0fd3cd Updated version and RELEASENOTES.md for release 0.5.3 2014-10-03 17:15:41 -07:00
Victor Sosa
0d79919aa5 CB-7700 cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser 2014-10-02 18:12:35 -05:00
Prabhjot Singh
a0785deff8 Amazon Specific changes:
Added logs and corrected indentation according to 81161ebe66
2014-10-02 12:20:22 -07:00
Victor Sosa
e9eb234683 CB-7471 cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser 2014-09-19 14:31:22 -05:00
sgrebnov
32c0e41c43 Windows implementation fixes and improvements 2014-09-19 10:33:53 +04:00
Piotr Zalewa
43592a4789 Merge branch 'fix_zindex' 2014-09-19 07:52:56 +02:00
Piotr Zalewa
4b3a838704 zIndex fixed 2014-09-19 07:51:42 +02:00
Jesse MacFadyen
ac0bdee8e6 renamed InAppBrowser back to inappbrowser for case sensitive operating systems 2014-09-18 16:52:40 -07:00
Jesse MacFadyen
22b3f0ccd4 Merge branch 'CB-5109' of https://github.com/Touchit/cordova-plugin-inappbrowser 2014-09-18 16:44:04 -07:00
Marcel Kinard
6e0ea336fc CB-7571 Bump version of nested plugin to match parent plugin 2014-09-17 16:27:16 -04:00
Marcel Kinard
f47f5449c2 CB-7571 Incremented plugin version. 2014-09-17 15:35:02 -04:00
Marcel Kinard
8ce6b497fa CB-7571 Updated version and RELEASENOTES.md for release 0.5.2 2014-09-17 15:27:43 -04:00
Lisa Seacat DeLuca
df90a6acc4 CB-7471 cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser 2014-09-15 17:26:46 -04:00
Jelle Kralt
720123718e Added option to disable/enable zoom controls
This change supports Android and Amazon Fire OS
2014-09-11 10:46:47 +02:00
Vladimir Kotikov
f90e571430 CB-7490 Fixes InAppBrowser manual tests crash on windows platform 2014-09-09 14:49:18 +04:00
Lisa Seacat DeLuca
ec8c4527b9 CB-7249 cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser 2014-09-04 22:31:14 -04:00
Shazron Abdullah
faf37db5da CB-7424 - Wrong docs: anchor tags are not supported by the InAppBrowser 2014-08-29 14:03:25 -07:00
Marcel Kinard
5fc1beed0d CB-7133 clarify that anchor1 doesn't exist 2014-08-27 17:15:55 -04:00
Marcel Kinard
832ff5f2e9 CB-7133 more fixup of tests on Android
- fix the paths to the injected resources
- update the urls to Google home page to use https to avoid redirects
- get the user agent to display on the inject.html page
2014-08-27 17:07:07 -04:00
Marcel Kinard
4f957919c7 CB-7133 fix up the tests for Android
- move the resources from /resources to /cdvtests/iab-resources
- change the url of the resources from absolute to relative
- explicitly set the background color of local.html to be white because it was inheriting black
- add the js to display the user-agent on the tests menu
- change the www.google.com URL from http to https to avoid an unexpected redirect
2014-08-27 15:57:33 -04:00
Marcel Kinard
81161ebe66 Add just a bit more logging 2014-08-27 14:11:43 -04:00
Staci Cooper
683937872d CB-7133 port inappbrowser to plugin-test-framework
also added resources and fixed file paths, renamed test dir, added nested plugin.xml

github: close 55
2014-08-27 10:43:01 -04:00
Piotr Zalewa
2c018a3460 Merge remote-tracking branch 'machard/events_suppport' 2014-08-27 13:48:50 +02:00
Piotr Zalewa
315a0e30db Merge remote-tracking branch 'machard/fixed_position' 2014-08-26 13:49:51 +02:00
Archana Naik
69ca780772 amazon-fireos related changes. 2014-08-14 11:57:44 -07:00
Steven Gill
79f73fbe62 CB-7244 Incremented plugin version. 2014-08-06 19:24:28 -07:00
Steven Gill
c37b08e038 CB-7244 Updated version and RELEASENOTES.md for release 0.5.1 2014-08-06 18:58:23 -07:00
Steven Gill
0900f5cc62 Merge branch 'master' of https://github.com/Zaspire/cordova-plugin-inappbrowser 2014-08-05 15:11:39 -07:00
Tracktl
97e0eac603 inappbrowser _blank target position is fixed 2014-08-05 15:53:45 +02:00
Tracktl
c2c94f315b phonegap events supported for _blank target 2014-08-05 15:50:49 +02:00
Lisa Seacat DeLuca
8cb876c63a CB-7249cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser 2014-08-01 16:24:03 -04:00
Willy Aguirre
cc2f8966ba update InAppBrowserProxy.js 2014-07-29 06:20:54 -05:00
Maxim Ermilov
f620b64035 ubuntu: support qt 5.2 2014-07-27 01:37:17 +04:00
SomaticIT
d828197de4 Clean plugin.xml 2014-07-11 21:54:25 +02:00
SomaticIT
6e38667320 Update french translation 2014-07-11 21:48:31 +02:00
SomaticIT
ea6a4fc80a Update doc to add Windows 8 2014-07-11 21:48:21 +02:00
SomaticIT
ac9c64964e Update windows proxy to be both compatible with windows 8 and 8.1 2014-07-11 21:43:37 +02:00
Piotr Zalewa
61239c12e8 Merge branch 'privileged_in_ffos' 2014-07-11 21:26:16 +02:00
Piotr Zalewa
9fe291ce7a app needs to be privileged 2014-07-11 19:40:03 +02:00
SomaticIT
225bde271b Rename windows81 by windows8 in src directory 2014-07-11 17:06:39 +02:00
SomaticIT
e5d07f14e8 Update code from remote apache repository 2014-07-11 17:05:24 +02:00
Lisa Seacat DeLuca
f866e0ed9f CB-6127lisa7cordova-plugin-consolecordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser 2014-07-07 15:27:50 -04:00
ldeluca
ae5e01ef04 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser 2014-07-07 11:09:48 -04:00
bwin
91b84579e8 CB-6769 ios: Fix statusbar color reset wasn't working on iOS7+
close #45
2014-06-27 14:33:33 -04:00
ldeluca
89ae9dbd53 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser 2014-06-11 09:58:52 -04:00
Steven Gill
c011fe2d9d CB-6877 Incremented plugin version. 2014-06-06 14:03:55 -07:00
Steven Gill
992306bbc5 CB-6877 Updated version and RELEASENOTES.md for release 0.5.0 2014-06-06 14:03:55 -07:00
Piotr Zalewa
384d3fb8a6 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser 2014-06-05 14:31:47 +02:00
Piotr Zalewa
f9c235caf5 Merge branch 'react_on_features' 2014-06-05 14:31:19 +02:00
Piotr Zalewa
df001e2765 after code review 2014-06-05 13:03:51 +02:00
Rodrigo Silveira
393524a3ea CB-6127 Spanish and rench Translations added. Github close #23 2014-06-04 16:05:10 -07:00
Andrew Grieve
eb704f8212 Clean up whitespace (mainly due to no newline at eof warning) 2014-06-04 14:25:50 -04:00
Piotr Zalewa
75cadab5ee Merge remote-tracking branch 'rodrigo/auto-permission' 2014-06-04 15:28:45 +02:00
Piotr Zalewa
846190a6f8 default parameter added 2014-06-04 15:24:21 +02:00
Piotr Zalewa
cd7916d025 Merge remote-tracking branch 'rodrigo/auto-permission' into react_on_features 2014-06-04 14:47:48 +02:00
Marcel Kinard
03e1715cfe CB-6806 Add license 2014-05-30 11:30:32 -04:00
Rodrigo Silveira
8fea6be60a Adding permission info 2014-05-28 12:36:59 -07:00
ldeluca
9fc6654b89 documentation translation: cordova-plugin-inappbrowser 2014-05-27 21:36:45 -04:00
ldeluca
1953356fd2 Lisa testing pulling in plugins for plugin: cordova-plugin-inappbrowser 2014-05-27 21:22:18 -04:00
ldeluca
687ce60470 Lisa testing pulling in plugins for plugin: cordova-plugin-inappbrowser 2014-05-27 17:49:43 -04:00
ldeluca
8e2db096ae Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser 2014-05-05 10:02:13 -04:00
Marcel Kinard
abf757edff CB-6491 add CONTRIBUTING.md 2014-04-30 09:30:38 -04:00
Kris Erickson
fea1f9827c Merge remote-tracking branch 'upstream/master' 2014-04-26 17:04:53 -07:00
Piotr Zalewa
5270462611 doc updated 2014-04-24 15:03:33 -04:00
Piotr Zalewa
a6cd0a16ba console.log removed 2014-04-24 15:01:09 -04:00
Piotr Zalewa
7b24dcb3dd back/forward buttons added, iframe has no border 2014-04-24 14:14:41 -04:00
Piotr Zalewa
282fdb7a40 not forcing the look of the inAppBrowserWrap and buttons 2014-04-24 10:51:06 -04:00
Piotr Zalewa
6ee35a09ca merged apache/dev 2014-04-23 11:05:10 -04:00
Jesse MacFadyen
be9034ff6c Merge branch 'enable-wp-capability' of https://github.com/Icenium/cordova-plugin-inappbrowser into dev 2014-04-21 18:18:52 -07:00
Jesse MacFadyen
e2a0bb8715 Merge branch 'CB-6474' of https://github.com/sgrebnov/cordova-plugin-inappbrowser into dev 2014-04-21 17:57:48 -07:00
Jesse MacFadyen
907bba6cf6 Merge branch 'CB-6482' of https://github.com/sgrebnov/cordova-plugin-inappbrowser into dev 2014-04-21 17:44:47 -07:00
sgrebnov
ab7494faa0 CB-6482 InAppBrowser calls incorrect callback on WP8 2014-04-21 15:28:03 -07:00
sgrebnov
8f2ad211ad CB-6474 InAppBrowser. Add data urls support to WP8 2014-04-18 10:47:20 -07:00
Shazron Abdullah
40778ba239 Fixed use of iOS 6 deprecated methods 2014-04-17 17:02:59 -07:00
Shazron Abdullah
c25bc30d7d CB-6360 - improvement: feature detection instead of iOS version detection 2014-04-17 16:52:21 -07:00
Shazron Abdullah
b9f8fcd8a9 CB-5649 - InAppBrowser overrides App's orientation 2014-04-17 16:32:40 -07:00
Ian Clelland
11f833b46d CB-6452 Incremented plugin version on dev branch. 2014-04-17 11:16:03 -04:00
Ian Clelland
1c98bc5b3f CB-6452 Updated version and RELEASENOTES.md for release 0.4.0 2014-04-17 10:53:20 -04:00
Ian Clelland
c5061ec333 CB-6460: Update license headers 2014-04-16 16:19:05 -04:00
Robin North
932f078e2d CB-6360: Fix for crash on iOS < 6.0 (closes #37) 2014-04-15 15:21:39 -07:00
Jesse MacFadyen
1c32236353 CB-3324 Add support for back-button inappbrowser [WP8] if there is no history -> InAppBrowser is closed 2014-04-14 17:11:36 -07:00
Jesse MacFadyen
34c29dc2ec await async calls, resolve warnings 2014-04-14 17:01:35 -07:00
Jesse MacFadyen
aa6c1519d2 Merge branch 'wp8-work-with-embedded-files' of https://github.com/Icenium/cordova-plugin-inappbrowser into dev 2014-04-14 12:20:35 -07:00
Nadya Atanasova
2fc9f3da1f Make InAppBrowser work with embedded files, using system behavior
The plugin is changed to work with embedded files, using the system behavior. If one needs the system behavior, they need to pass "_system" as target when using the plugin. As the InAppBrowser for WP8 does not handle by itself the embedded pdf files, system behavior is called.

The plugin also is tested and working for wp7
2014-04-11 17:57:45 +03:00
Jesse MacFadyen
bddf86c3ce CB-6402 [WP8] pass empty string instead of null for [optional] windowFeatures string 2014-04-09 12:26:47 -07:00
Piotr Zalewa
cc5b0ce5a3 Merge pull request #2 from zalun/close-button-fix
CB-6396 Fix refactoring typo
2014-04-09 15:18:36 +02:00
Piotr Zalewa
88f330abd8 refactoring fixed 2014-04-09 15:16:52 +02:00
Jesse MacFadyen
25f306d11e CB-6422 [windows8] use cordova/exec/proxy 2014-04-08 16:29:32 -07:00
Ian Clelland
04de070dcd CB-3617: Document clearcache and clearsessioncache for ios 2014-04-07 10:10:12 -06:00
Gert-Jan Braas
c14871da95 Merge pull request #1 from zalun/add-firefoxos-plugin
CB-6396 [Firefox OS] Adding basic support
2014-04-07 17:06:54 +02:00
Piotr Zalewa
51879d8e2f CB-6396 [Firefox OS] Adding basic support 2014-04-04 12:16:01 +02:00
mbradshawabs
22c7a0e51e CB-6389 CB-3617: Add clearcache and clearsessioncache options to iOS (like Android) 2014-04-02 15:04:48 -04:00
Nadya Atanasova
bdf4ade2bb Add necessary capability so the plugin works on its own 2014-03-31 16:36:18 +03:00
ldeluca
6b25158e07 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser 2014-03-28 12:10:27 -04:00
Rocco Georgi
9399ed3955 Doc update: event name and example param (closes #31) 2014-03-24 15:42:53 -07:00
Jesse MacFadyen
749d55c676 CB-6253 Add Network Capability to WMAppManifest.xml 2014-03-19 22:26:01 -07:00
James Jong
fceea502a3 CB-6212 iOS: fix warnings compiled under arm64 64-bit 2014-03-12 13:35:17 -04:00
Bryan Higgins
aa9a5db941 CB-6218 Update docs for BB10 2014-03-11 12:22:37 -04:00
Bryan Higgins
e282cc9e38 CB-6218 Update docs for BB10 2014-03-11 12:22:17 -04:00
Kris Erickson
392a73c2cd Add a hardwareback option to allow for the hardware back button to go back. 2014-03-09 11:33:24 -07:00
Andrew Grieve
7dbad601f0 Tweak RELEASENOTES.md (missed a bug fix in last release) 2014-03-06 20:48:00 -05:00
Andrew Grieve
5680f18bb4 Incremented plugin version on dev branch. 2014-03-05 14:38:13 -05:00
Andrew Grieve
a5dedae631 Updated version and RELEASENOTES.md for release 0.3.3 2014-03-05 14:37:10 -05:00
Andrew Grieve
d0dd10103c CB-6172 Fix inappbrowser install failure on case-sensitive filesystems. 2014-03-05 12:34:31 -05:00
ldeluca
34653ce393 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser 2014-03-04 12:43:38 -05:00
Joe Bowser
497a23efc7 CB-5534: Updating the plugin.xml with the new Dialog class 2014-02-28 14:04:25 -08:00
Oliver Moran
6f373f7ed9 fix for CB-5534
Signed-off-by: Joe Bowser <bowserj@apache.org>
2014-02-28 14:04:25 -08:00
Andrew Grieve
300f1e782e Merge branch 'master' into dev 2014-02-27 16:04:39 -05:00
Andrew Grieve
4d3c7b17d2 Add NOTICE file 2014-02-27 15:45:10 -05:00
Andrew Grieve
a5201cc1e3 Add NOTICE file 2014-02-27 15:36:31 -05:00
Andrew Grieve
942d17981e CB-6114 Incremented plugin version on dev branch. 2014-02-27 12:29:15 -05:00
Andrew Grieve
17ba417572 Merge branch 'master' into dev
Conflicts:
	RELEASENOTES.md
	plugin.xml
2014-02-27 12:01:26 -05:00
Andrew Grieve
77085aa547 CB-6114 Updated version and RELEASENOTES.md for release 0.3.2 2014-02-27 11:56:29 -05:00
ldeluca
4a3c134be1 Lisa testing pulling in plugins for plugin: cordova-plugin-inappbrowser 2014-02-27 11:14:55 -05:00
ldeluca
dbf54d2d09 Lisa testing pulling in plugins for plugin: cordova-plugin-inappbrowser 2014-02-26 09:36:16 -05:00
Ian Clelland
26702cb072 Validate that callbackId is correctly formed 2014-02-19 00:26:19 -05:00
Bryan Higgins
39e64c988a CB-6035 - Move js-module so it is not loaded on unsupported platforms
BlackBerry 10 has a native implementation which does not require the plugin.
2014-02-13 15:00:18 -05:00
Steven Gill
cd31b3a64d CB-5980 Incremented plugin version on dev branch. 2014-02-10 15:23:01 -08:00
Steven Gill
4c07917c0a CB-5980 Updated version and RELEASENOTES.md for release 0.3.1 2014-02-10 15:23:01 -08:00
Sidney Bofah
24e6a1feeb Removed some iOS6 Deprecations 2014-02-10 15:37:23 -05:00
Steven Gill
b62b9edde3 CB-5980 Updated version and RELEASENOTES.md for release 0.3.1 2014-02-05 17:53:59 -08:00
Andrew Grieve
985d94ee00 Add missing import for previous commit 2014-01-19 21:56:59 -05:00
Ian Clelland
e807bc3dc0 CB-5756: Android: Use WebView.evaluateJavascript for script injection on Android 4.4+ 2014-01-19 21:22:02 -05:00
Joe Bowser
0ce0eed585 Didn't test on ICS or lower, getDrawable isn't supported until Jellybean 2014-01-16 13:55:53 -08:00
Joe Bowser
736c8ddec0 WTF? ubuntu got automerged twice 2014-01-16 11:34:47 -08:00
Maxim Ermilov
9206d82df4 add ubuntu platform 2014-01-16 11:33:45 -08:00
Joe Bowser
bc554fdf95 Adding CC-A-2.5 Notice for Assets, modifying plugins to use resources 2014-01-16 11:33:44 -08:00
Joe Bowser
43f8935541 Adding the buttons 2014-01-16 11:33:44 -08:00
Joe Bowser
2136cad49a Adding drawables to the inAppBrowser. This doesn't look quite right, but it's a HUGE improvement over the previous settings 2014-01-16 11:33:44 -08:00
Ian Clelland
9795b2e9dc CB-5756: Add missing import 2014-01-13 15:09:38 -05:00
Ian Clelland
255c5269c3 CB-5756: Android: Use WebView.evaluateJavascript for script injection on Android 4.4+ 2014-01-13 14:34:32 -05:00
Andrew Grieve
21fe13e809 Delete stale test/ directory 2014-01-08 21:11:43 -05:00
Andrew Grieve
3f9af4fd88 Remove _alive from InAppBrowser.js since it didn't catch the case where the browser is closed by the user. 2014-01-07 10:52:44 -05:00
Andrew Grieve
57d14da151 CB-5733 Fix IAB.close() not working if called before show() animation is done
Also attempts to fix some thread warnings by doing show/hide on
separate event loop cycles.
2014-01-07 10:52:38 -05:00
Andrew Grieve
21a1638ccf CB-5719 Incremented plugin version on dev branch. 2014-01-02 12:30:52 -05:00
Andrew Grieve
b0bdb1088b CB-5719 Updated version and RELEASENOTES.md for release 0.3.0 2014-01-02 12:24:02 -05:00
Andrew Grieve
6163f17aeb CB-5592 Add a comment explaining why we set MIME only for file: 2013-12-20 11:10:33 -05:00
gianluca
176890f305 CB-5592 Android - Add MIME type to Intent when opening file:/// URLs
To avoid the "No Activity found to handle Intent..." error.
2013-12-20 11:06:10 -05:00
Andrew Grieve
2bd006b71e CB-5658 Update license comment formatting of doc/index.md 2013-12-18 21:11:02 -05:00
Andrew Grieve
aac2db29b5 CB-5658 Add doc.index.md for InAppBrowser plugin 2013-12-18 15:31:18 -05:00
Andrew Grieve
97c6f2ba8a CB-5658 Delete stale snapshot of plugin docs 2013-12-17 20:49:39 -05:00
ivan baktsheev
f75b30857b CB-5594 Add disallowoverscroll option.
Similar to the main cordova webview
2013-12-13 09:25:46 -05:00
Andrew Grieve
25d152b578 CB-5595 Rename "toolbarbarpostion" -> "toolbarposition" 2013-12-13 09:17:49 -05:00
Peter Somogyvari
4aeaf81e1e CB-5595 Fixed the positioning and autoresizing for certain rotation scenarios.
The autoresizing masks are applied conditonally based on the
browserOptions.toolbarposition flag to ensure that the toolbar is in
its correct place. Also added a utility function to query the
necessary offset for the status bar: the function takes care of the iOS
version and orientation caused differences without hardcoding the value
as 20 pixels.
2013-12-13 09:17:11 -05:00
Peter Somogyvari
20611efe67 CB-5595 Add toolbarposition=top option.
The position of the toolbar is now configurable, it can be specified on
the caller's side. The possible values are top and bottom and the key
for the setting is toolbarposition. Also extended the logging of the web
view's load errors, it now logs the error code too, not just the
localized description of the error that occured. Added the
browserOptions to the init method's parameters in order to make it
conveniently accessible from the ViewController.
2013-12-13 09:16:04 -05:00
Dick van den Brink
e819041fd4 Apply CB-5193 to InAppBrowser
From pull request:
https://github.com/apache/cordova-plugin-inappbrowser/pull/11
2013-12-06 10:07:41 -05:00
Tomáš Fejfar
034b599315 CB-5593 iOS: Make InAppBrowser localizable
Wrapping all UI strings in NSLocalizedString macro
2013-12-06 09:42:22 -05:00
Fco. Javier Martín Carrasco
f448ce88ab CB-5591 Change window.escape to encodeURIComponent
escape is for JS, encodeURIComponent is for URLs. This is a URL.
2013-12-06 09:14:15 -05:00
Steven Gill
ea239151d2 [CB-5565] Incremented plugin version on dev branch. 2013-12-04 15:32:03 -08:00
Steven Gill
496ecc720f [CB-5565] Updated version and RELEASENOTES.md for release 0.2.5 2013-12-04 15:16:31 -08:00
Jesse MacFadyen
30525d545a Merge branch 'dev' of https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser into dev 2013-12-03 13:50:16 -08:00
Jesse MacFadyen
8a549547cb Merge branch 'dev' of https://github.com/Yangtb/cordova-plugin-inappbrowser into dev 2013-12-03 13:42:50 -08:00
Ian Clelland
65ee3d142f Remove merge conflict tag 2013-12-02 20:53:17 -05:00
Jesse MacFadyen
fadb170e50 Merge branch 'dev' of https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser into dev 2013-12-02 17:51:28 -08:00
Jesse MacFadyen
9768ec2ef0 CB-3420 WP feature hidden=yes implemented 2013-12-02 17:50:57 -08:00
Steven Gill
d2b644e5d5 Added ubuntu support 2013-12-02 16:28:32 -08:00
Archana Naik
e5101ba8e1 Added amazon-fireos platform.
Change to use amazon-fireos as the platform if user agent string contains 'cordova-amazon-fireos'
2013-10-30 13:36:04 -07:00
Steven Gill
d49d6ec62f CB-5188: 2013-10-28 12:27:15 -07:00
Steven Gill
a8060219d5 fixed merge conflict 2013-10-28 12:13:43 -07:00
Steven Gill
e5868f8ecb [CB-5188] Updated version and RELEASENOTES.md for release 0.2.4 2013-10-28 12:03:26 -07:00
hermwong
b3348cff6c CB-5128: added repo + issue tag to plugin.xml for inappbrowser plugin 2013-10-22 13:40:00 -07:00
Andrew Grieve
aa81c3267a CB-4995 Fix crash when WebView is quickly opened then closed.
Also fixes a leak where callback was never being cleared.
2013-10-21 13:19:13 -04:00
SomaticIT
863386398e Append Windows 8.1 platform configuration in plugin.xml 2013-10-17 23:02:59 +02:00
SomaticIT
ef9ca5ad3e Append Windows 8.1 proxy using x-ms-webview 2013-10-17 23:01:13 +02:00
Maxim Ermilov
a8f79e1fd6 add ubuntu platform 2013-10-16 21:13:03 +04:00
Shazron Abdullah
c7972b6cff CB-4930 - iOS - InAppBrowser should take into account the status bar 2013-10-15 15:00:09 -07:00
Steven Gill
ce7a796cb0 [CB-5010] Incremented plugin version on dev branch. 2013-10-10 10:56:18 -07:00
Steven Gill
a76a0a3920 [CB-5010] Updated version and RELEASENOTES.md for release 0.2.3 2013-10-10 10:56:18 -07:00
Andrew Grieve
5ef5171003 CB-4858 - Run IAB methods on the UI thread. 2013-10-10 12:40:27 -04:00
Andrew Grieve
8a6bc01814 CB-4858 Convert relative URLs to absolute URLs in JS 2013-10-10 12:21:35 -04:00
Andrew Grieve
8df4b7d03b CB-3747 Fix back button having different dismiss logic from the close button.
Also made the IAB close when the owner page is navigated (implemented
onReset).
2013-10-10 11:51:58 -04:00
Andrew Grieve
8cd786b603 CB-5021 Expose closeDialog() as a public function and make it safe to call multiple times. 2013-10-10 08:07:46 -04:00
Andrew Grieve
ef5eddac9a CB-5021 Make it safe to call close() multiple times 2013-10-09 21:25:24 -04:00
Steven Gill
4d4d479b3c [CB-5010] Updated version and RELEASENOTES.md for release 0.2.3 2013-10-09 15:27:18 -07:00
Steven Gill
3d8b04f982 [CB-4915] Incremented plugin version on dev branch. 2013-09-26 15:26:55 -07:00
Carlos Santana
12bc5d7d8b [CB-4926] Fixes inappbrowser plugin loading for windows8 2013-09-26 13:53:33 -04:00
Yangtb
e5862bf820 [CB-4724] fixed UriFormatException
fixed UriFormatException & InvalidOperationException
2013-09-11 16:18:47 +08:00
80 changed files with 11488 additions and 1813 deletions

37
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,37 @@
<!--
#
# 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.
#
-->
# Contributing to Apache Cordova
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.
- Run the tests so your patch doesn't break existing functionality.
We look forward to your contributions!

5
NOTICE Normal file
View File

@@ -0,0 +1,5 @@
Apache Cordova
Copyright 2012 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).

396
README.md
View File

@@ -1,5 +1,393 @@
cordova-plugin-inappbrowser
-----------------------------
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).
<!--
# 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.
-->
If you are not using the Cordova Command-line Interface, follow [Using Plugman to Manage Plugins](http://cordova.apache.org/docs/en/edge/plugin_ref_plugman.md.html).
# cordova-plugin-inappbrowser
This plugin provides a web browser view that displays when calling `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
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;
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
into the main Cordova webview. The InAppBrowser is not subject to the
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");
}
:warning: Report issues 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)
## Installation
cordova plugin add cordova-plugin-inappbrowser
If you want all page loads in your app to go through the InAppBrowser, you can
simply hook `window.open` during initialization. For example:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Opens a URL in a new `InAppBrowser` instance, the current browser
instance, or the system browser.
var ref = cordova.InAppBrowser.open(url, target, options);
- __ref__: Reference to the `InAppBrowser` window. _(InAppBrowser)_
- __url__: The URL to load _(String)_. Call `encodeURI()` on this if the URL contains Unicode characters.
- __target__: The target in which to load the URL, an optional parameter that defaults to `_self`. _(String)_
- `_self`: Opens in the Cordova WebView if the URL is in the white list, otherwise it opens in the `InAppBrowser`.
- `_blank`: Opens in the `InAppBrowser`.
- `_system`: Opens in the system's web 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:
- __location__: Set to `yes` or `no` to turn the `InAppBrowser`'s location bar on or off.
Android only:
- __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.
- __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`.
- __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.
iOS only:
- __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.
- __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
- __toolbar__: set to `yes` or `no` to turn the toolbar on or off for the InAppBrowser (defaults to `yes`)
- __enableViewportScale__: Set to `yes` or `no` to prevent viewport scaling through a meta tag (defaults to `no`).
- __mediaPlaybackRequiresUserAction__: Set to `yes` or `no` 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`).
- __toolbarposition__: Set to `top` or `bottom` (default is `bottom`). Causes the toolbar to be at the top or bottom of the window.
Windows only:
- __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.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
### 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;
}
```
### 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,
- Navigation history (`back` and `forward` buttons in LocationBar) is not implemented.
## InAppBrowser
The object returned from a call to `cordova.InAppBrowser.open`.
### Methods
- addEventListener
- removeEventListener
- close
- show
- executeScript
- insertCSS
## addEventListener
> Adds a listener for an event from the `InAppBrowser`.
ref.addEventListener(eventname, callback);
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
- __eventname__: the event to listen for _(String)_
- __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.
- __callback__: the function that executes when the event fires. The function is passed an `InAppBrowserEvent` object as a parameter.
### InAppBrowserEvent Properties
- __type__: the eventname, either `loadstart`, `loadstop`, `loaderror`, or `exit`. _(String)_
- __url__: the URL that was loaded. _(String)_
- __code__: the error code, only in the case of `loaderror`. _(Number)_
- __message__: the error message, only in the case of `loaderror`. _(String)_
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
### Browser Quirks
`loadstart` and `loaderror` events are not being fired.
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Removes a listener for an event from the `InAppBrowser`.
ref.removeEventListener(eventname, callback);
- __ref__: reference to the `InAppBrowser` window. _(InAppBrowser)_
- __eventname__: the event to stop listening for. _(String)_
- __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 loading a URL.
- __exit__: event fires when the `InAppBrowser` window is closed.
- __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
### Quick Example
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
> Closes the `InAppBrowser` window.
ref.close();
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
### Supported Platforms
- Amazon Fire OS
- Android
- Firefox OS
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> Displays an InAppBrowser window that was opened hidden. Calling this has no effect if the InAppBrowser was already visible.
ref.show();
- __ref__: reference to the InAppBrowser window (`InAppBrowser`)
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Browser
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Injects JavaScript code into the `InAppBrowser` window
ref.executeScript(details, callback);
- __ref__: reference to the `InAppBrowser` window. _(InAppBrowser)_
- __injectDetails__: details of the script to run, specifying either a `file` or `code` key. _(Object)_
- __file__: URL of the script to inject.
- __code__: Text of the script to inject.
- __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.
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Browser
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### Browser Quirks
- only __code__ key is supported.
### Windows Quirks
Due to [MSDN docs](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx) the invoked script can return only string values, otherwise the parameter, passed to __callback__ will be `[null]`.
## insertCSS
> Injects CSS into the `InAppBrowser` window.
ref.insertCSS(details, callback);
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
- __injectDetails__: details of the script to run, specifying either a `file` or `code` key. _(Object)_
- __file__: URL of the stylesheet to inject.
- __code__: Text of the stylesheet to inject.
- __callback__: the function that executes after the CSS is injected.
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});

View File

@@ -20,15 +20,209 @@
-->
# Release Notes
### 1.2.1 (Feb 02, 2016)
* [CB-10407](https://issues.apache.org/jira/browse/CB-10407) InAppBrowser not firing loadstart event on android
* [CB-10428](https://issues.apache.org/jira/browse/CB-10428) Fix syntax error when browserifying inAppBrowser plugin
* handle app store urls in system browser
* [CB-6702](https://issues.apache.org/jira/browse/CB-6702) InAppBrowser hangs when opening more than one instance
* [CB-10456](https://issues.apache.org/jira/browse/CB-10456) InAppBrowser is not closed if I close it programmatically on Android
* [CB-10451](https://issues.apache.org/jira/browse/CB-10451) InAppBrowser: loadstart event is not triggered on Windows
* [CB-10452](https://issues.apache.org/jira/browse/CB-10452) InAppBrowser: 'exit' event is not triggered on Windows
* [CB-10454](https://issues.apache.org/jira/browse/CB-10454) InAppBrowser: 'loaderror' event does not have code and message on Windows
* [CB-10450](https://issues.apache.org/jira/browse/CB-10450) InAppBrowser: Unable to get property 'canGoBack' of undefined on Windows
* [CB-10441](https://issues.apache.org/jira/browse/CB-10441) Add auto tests for InAppBrowser plugin
### 1.2.0 (Jan 15, 2016)
* CB-8180: Changing methods of interception in `WebViewClient` class
* CB-10009 Improve `InAppBrowser` toolbar look and feel on **Windows**
* Open a new window on the **Browser** platform
### 1.1.1 (Dec 10, 2015)
* CB-9445 Improves executeScript callbacks on iOS
* CB-10035 Incremented plugin version.
* CB-10040 - re-fix: backwards compatible with cordova-ios < 4.0
* CB-8534: Allow plugins to respond to onReceivedHttpAuthRequest. This closes #82
* CB-3750: Fixes spinner on iOS. This closes #89
* CB-7696 Document target=_self behavior for Windows
* CB-10040 - Compile Error in InAppBrowser Plugin for iOS - No known instance method for selector 'URLIsWhitelisted:'
### 1.1.0 (Nov 18, 2015)
* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest
* Invoke webview if using local file
* Fixed `zIndex` issue on **Windows 8**, **8.188 where InAppBrowser opens behind default app.
* fix `async` self usage
* [CB-9150](https://issues.apache.org/jira/browse/CB-9150) Fix InAppBrowser `executeScript` crash on **Windows** if no data returned
* [CB-10008](https://issues.apache.org/jira/browse/CB-10008) Fix InAppBrowser popup layout on **Windows**
* Setting `setStatusBarStyle` to `-1` causes `CGContextSaveGState`.
* [CB-9167](https://issues.apache.org/jira/browse/CB-9167) Fix crash on **browser** window close
* [CB-9799](https://issues.apache.org/jira/browse/CB-9799) Fixed `javaDoc` errors.
* Fixing contribute link.
* [CB-9760](https://issues.apache.org/jira/browse/CB-9760) InAppBrowser: fallback to default `window.open` behavior on **Ripple**
* [CB-9378](https://issues.apache.org/jira/browse/CB-9378) Fix InAppBrowser not taking whole screen on **Windows**
* [CB-9158](https://issues.apache.org/jira/browse/CB-9158) - InAppBrowser `zoomControls` are always set to true
### 1.0.1 (Jun 17, 2015)
* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser
* fix npm md issue
### 1.0.0 (Apr 15, 2015)
* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump
* [CB-7689](https://issues.apache.org/jira/browse/CB-7689) Adds insertCSS support for windows platform
* [CB-4930](https://issues.apache.org/jira/browse/CB-4930) - (prefix) InAppBrowser should take into account the status bar
* [CB-8635](https://issues.apache.org/jira/browse/CB-8635) Improves UX on windows platform
* [CB-8661](https://issues.apache.org/jira/browse/CB-8661) Return executed script result on Windows
* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) updated wp and browser specific references of old id to new id
* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name
* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id
* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id
* Use TRAVIS_BUILD_DIR, install paramedic by npm
* [CB-8432](https://issues.apache.org/jira/browse/CB-8432) Correct styles for browser wrapper to display it correctly on some pages
* [CB-8659](https://issues.apache.org/jira/browse/CB-8659) - Update InAppBrowser to support both cordova-ios 4.0.x and 3.x (closes #93)
* [CB-7961](https://issues.apache.org/jira/browse/CB-7961) Add cordova-plugin-inappbrowser support for browser platform
* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme
* Update docs for Android zoom=no option
* Added option to disable/enable zoom controls
* updated docs, set hardwareback default to true
* Add a hardwareback option to allow for the hardware back button to go back.
* [CB-8570](https://issues.apache.org/jira/browse/CB-8570) Integrate TravisCI
* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser
* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file
* Keep external android pages in a single tab. (close #61)
* [CB-8444](https://issues.apache.org/jira/browse/CB-8444) Add a clobber for `cordova.InAppBrowser.open` (close #80)
* [CB-8444](https://issues.apache.org/jira/browse/CB-8444) Don't clobber `window.open` - Add new symbol/clobber to access open function (`cordova.InAppBrowser.open`) - Change existing tests to use new symbol (i.e. don't rely on plugin clobber of `window.open`) - Add tests to use `window.open` via manual replace with new symbol - Update docs to deprecate plugin clobber of `window.open`
### 0.6.0 (Feb 04, 2015)
* [CB-8270](https://issues.apache.org/jira/browse/CB-8270) ios: Remove usage of `[arr JSONString]`, since it's been renamed to `cdv_JSONString`
* ubuntu: implement `inject*` functions
* ubuntu: port to oxide
* [CB-7897](https://issues.apache.org/jira/browse/CB-7897) ios, android: Update to work with whilelist plugins in Cordova 4.x
### 0.5.4 (Dec 02, 2014)
* [CB-7784](https://issues.apache.org/jira/browse/CB-7784) Exit event is not fired after `InAppBrowser` closing
* [CB-7697](https://issues.apache.org/jira/browse/CB-7697) Add `locationBar` support to `InAppBrowser` **Windows** platform version
* [CB-7690](https://issues.apache.org/jira/browse/CB-7690) `InAppBrowser` `loadstart/loadstop` events issues
* [CB-7695](https://issues.apache.org/jira/browse/CB-7695) Fix `InAppBrowser` `injectScriptFile` for **Windows 8.1** / **Windows Phone 8.1**
* [CB-7692](https://issues.apache.org/jira/browse/CB-7692) `InAppBrowser` local url opening bug in 8.1
* [CB-7688](https://issues.apache.org/jira/browse/CB-7688) `Alert` is not supported in `InAppBrowser` on **Windows** platform
* [CB-7977](https://issues.apache.org/jira/browse/CB-7977) Mention `deviceready` in plugin docs
* [CB-7876](https://issues.apache.org/jira/browse/CB-7876) change test target to avoid undesired redirects
* [CB-7712](https://issues.apache.org/jira/browse/CB-7712) remove references to `closebuttoncaption`
* [CB-7850](https://issues.apache.org/jira/browse/CB-7850) clarify role of whitelist
* [CB-7720](https://issues.apache.org/jira/browse/CB-7720) check if event is null since OK string from success callback was removed
* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser
### 0.5.3 (Oct 03, 2014)
* Windows implementation fixes and improvements
* zIndex fixed
* renamed InAppBrowser back to inappbrowser for case sensitive operating systems
* Update french translation
* Update doc to add Windows 8
* Update windows proxy to be both compatible with windows 8 and 8.1
* Rename windows81 by windows8 in src directory
* Append Windows 8.1 platform configuration in plugin.xml
* Append Windows 8.1 proxy using x-ms-webview
### 0.5.2 (Sep 17, 2014)
* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser
* [CB-7490](https://issues.apache.org/jira/browse/CB-7490) Fixes InAppBrowser manual tests crash on windows platform
* [CB-7249](https://issues.apache.org/jira/browse/CB-7249) cordova-plugin-inappbrowser documentation translation: cordova-plugin-inappbrowser
* [CB-7424](https://issues.apache.org/jira/browse/CB-7424) Wrong docs: anchor tags are not supported by the InAppBrowser
* [CB-7133](https://issues.apache.org/jira/browse/CB-7133) clarify that anchor1 doesn't exist
* [CB-7133](https://issues.apache.org/jira/browse/CB-7133) more fixup of tests on Android
* [CB-7133](https://issues.apache.org/jira/browse/CB-7133) fix up the tests for Android
* Add just a bit more logging
* [CB-7133](https://issues.apache.org/jira/browse/CB-7133) port inappbrowser to plugin-test-framework
* phonegap events supported for \_blank target
* inappbrowser \_blank target position is fixed
* amazon-fireos related changes.
### 0.5.1 (Aug 06, 2014)
* ubuntu: support qt 5.2
* **FFOS** update InAppBrowserProxy.js
* **FFOS** app needs to be privileged
* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs
* [CB-6769](https://issues.apache.org/jira/browse/CB-6769) ios: Fix statusbar color reset wasn't working on iOS7+
### 0.5.0 (Jun 05, 2014)
* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Spanish and rench Translations added. Github close #23
* Clean up whitespace (mainly due to no newline at eof warning)
* Adding permission info
* [CB-6806](https://issues.apache.org/jira/browse/CB-6806) Add license
* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md
* Add necessary capability so the plugin works on its own
* [CB-6474](https://issues.apache.org/jira/browse/CB-6474) InAppBrowser. Add data urls support to WP8
* [CB-6482](https://issues.apache.org/jira/browse/CB-6482) InAppBrowser calls incorrect callback on WP8
* Fixed use of iOS 6 deprecated methods
* [CB-6360](https://issues.apache.org/jira/browse/CB-6360) - improvement: feature detection instead of iOS version detection
* [CB-5649](https://issues.apache.org/jira/browse/CB-5649) - InAppBrowser overrides App's orientation
* refactoring fixed
* [CB-6396](https://issues.apache.org/jira/browse/CB-6396) [Firefox OS] Adding basic support
### 0.4.0 (Apr 17, 2014)
* [CB-6360](https://issues.apache.org/jira/browse/CB-6360): [ios] Fix for crash on iOS < 6.0 (closes #37)
* [CB-3324](https://issues.apache.org/jira/browse/CB-3324): [WP8] Add support for back-button inappbrowser [WP8] if there is no history -> InAppBrowser is closed
* [WP] await async calls, resolve warnings
* [WP] Make InAppBrowser work with embedded files, using system behavior
* [CB-6402](https://issues.apache.org/jira/browse/CB-6402): [WP8] pass empty string instead of null for [optional] windowFeatures string
* [CB-6422](https://issues.apache.org/jira/browse/CB-6422): [windows8] use cordova/exec/proxy
* [CB-6389](https://issues.apache.org/jira/browse/CB-6389) [CB-3617](https://issues.apache.org/jira/browse/CB-3617): Add clearcache and clearsessioncache options to iOS (like Android)
* Doc update: event name and example param (closes #31)
* [CB-6253](https://issues.apache.org/jira/browse/CB-6253): [WP] Add Network Capability to WMAppManifest.xml
* [CB-6212](https://issues.apache.org/jira/browse/CB-6212): [iOS] fix warnings compiled under arm64 64-bit
* [CB-6218](https://issues.apache.org/jira/browse/CB-6218): Update docs for BB10
* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers
### 0.3.3 (Mar 5, 2014)
* [CB-5534](https://issues.apache.org/jira/browse/CB-5534) Fix video/audio does not stop playing when browser is closed
* [CB-6172](https://issues.apache.org/jira/browse/CB-6172) Fix broken install on case-sensitive file-systems
### 0.3.2 (Feb 26, 2014)
* Validate that callbackId is correctly formed
* [CB-6035](https://issues.apache.org/jira/browse/CB-6035) Move js-module so it is not loaded on unsupported platforms
* Removed some iOS6 Deprecations
### 0.3.1 (Feb 05, 2014)
* [CB-5756](https://issues.apache.org/jira/browse/CB-5756): Android: Use WebView.evaluateJavascript for script injection on Android 4.4+
* Didn't test on ICS or lower, getDrawable isn't supported until Jellybean
* add ubuntu platform
* Adding drawables to the inAppBrowser. This doesn't look quite right, but it's a HUGE improvement over the previous settings
* [CB-5756](https://issues.apache.org/jira/browse/CB-5756): Android: Use WebView.evaluateJavascript for script injection on Android 4.4+
* Remove alive from InAppBrowser.js since it didn't catch the case where the browser is closed by the user.
* [CB-5733](https://issues.apache.org/jira/browse/CB-5733) Fix IAB.close() not working if called before show() animation is done
### 0.2.5 (Dec 4, 2013)
* Remove merge conflict tag
* [CB-4724](https://issues.apache.org/jira/browse/CB-4724) fixed UriFormatException
* add ubuntu platform
* [CB-3420](https://issues.apache.org/jira/browse/CB-3420) WP feature hidden=yes implemented
* Added amazon-fireos platform. Change to use amazon-fireos as the platform if user agent string contains 'cordova-amazon-fireos'
### 0.2.4 (Oct 28, 2013)
* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag to plugin.xml for inappbrowser plugin
* [CB-4995](https://issues.apache.org/jira/browse/CB-4995) Fix crash when WebView is quickly opened then closed.
* [CB-4930](https://issues.apache.org/jira/browse/CB-4930) - iOS - InAppBrowser should take into account the status bar
* [CB-5010](https://issues.apache.org/jira/browse/CB-5010) Incremented plugin version on dev branch.
* [CB-5010](https://issues.apache.org/jira/browse/CB-5010) Updated version and RELEASENOTES.md for release 0.2.3
* [CB-4858](https://issues.apache.org/jira/browse/CB-4858) - Run IAB methods on the UI thread.
* [CB-4858](https://issues.apache.org/jira/browse/CB-4858) Convert relative URLs to absolute URLs in JS
* [CB-3747](https://issues.apache.org/jira/browse/CB-3747) Fix back button having different dismiss logic from the close button.
* [CB-5021](https://issues.apache.org/jira/browse/CB-5021) Expose closeDialog() as a public function and make it safe to call multiple times.
* [CB-5021](https://issues.apache.org/jira/browse/CB-5021) Make it safe to call close() multiple times
### 0.2.3 (Oct 9, 2013)
* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch.
* [CB-4926](https://issues.apache.org/jira/browse/CB-4926) Fixes inappbrowser plugin loading for windows8
### 0.2.2 (Sept 25, 2013)
* CB-4889 bumping&resetting version
* CB-4788: Modified the onJsPrompt to warn against Cordova calls
* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version
* [CB-4788](https://issues.apache.org/jira/browse/CB-4788): Modified the onJsPrompt to warn against Cordova calls
* [windows8] commandProxy was moved
* CB-4788: Modified the onJsPrompt to warn against Cordova calls
* [CB-4788](https://issues.apache.org/jira/browse/CB-4788): Modified the onJsPrompt to warn against Cordova calls
* [windows8] commandProxy was moved
* CB-4889 renaming core references
* CB-4889 renaming org.apache.cordova.core.inappbrowser to org.apache.cordova.inappbrowser
* CB-4864, CB-4865: Minor improvements to InAppBrowser
* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming core references
* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.inappbrowser to org.apache.cordova.inappbrowser
* [CB-4864](https://issues.apache.org/jira/browse/CB-4864), [CB-4865](https://issues.apache.org/jira/browse/CB-4865): Minor improvements to InAppBrowser
* Rename CHANGELOG.md -> RELEASENOTES.md
* [CB-4792] Added keepCallback to the show function.
* [CB-4752] Incremented plugin version on dev branch.
* [CB-4792](https://issues.apache.org/jira/browse/CB-4792) Added keepCallback to the show function.
* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch.

388
doc/de/README.md Normal file
View File

@@ -0,0 +1,388 @@
<!--
# 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"});
});

357
doc/de/index.md Normal file
View File

@@ -0,0 +1,357 @@
<!---
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"});
});

388
doc/es/README.md Normal file
View File

@@ -0,0 +1,388 @@
<!--
# 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"});
});

357
doc/es/index.md Normal file
View File

@@ -0,0 +1,357 @@
<!---
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"});
});

388
doc/fr/README.md Normal file
View File

@@ -0,0 +1,388 @@
<!--
# 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"});
});

357
doc/fr/index.md Normal file
View File

@@ -0,0 +1,357 @@
<!---
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"});
});

388
doc/it/README.md Normal file
View File

@@ -0,0 +1,388 @@
<!--
# 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"});
});

357
doc/it/index.md Normal file
View File

@@ -0,0 +1,357 @@
<!---
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"});
});

388
doc/ja/README.md Normal file
View File

@@ -0,0 +1,388 @@
<!--
# 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"});
});

357
doc/ja/index.md Normal file
View File

@@ -0,0 +1,357 @@
<!---
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"});
});

388
doc/ko/README.md Normal file
View File

@@ -0,0 +1,388 @@
<!--
# 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"});
});

357
doc/ko/index.md Normal file
View File

@@ -0,0 +1,357 @@
<!---
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"});
});

388
doc/pl/README.md Normal file
View File

@@ -0,0 +1,388 @@
<!--
# 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"});
});

357
doc/pl/index.md Normal file
View File

@@ -0,0 +1,357 @@
<!---
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"});
});

330
doc/ru/index.md Normal file
View File

@@ -0,0 +1,330 @@
<!---
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"});
});

388
doc/zh/README.md Normal file
View File

@@ -0,0 +1,388 @@
<!--
# 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"});
});

357
doc/zh/index.md Normal file
View File

@@ -0,0 +1,357 @@
<!---
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,427 +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.
---
InAppBrowser
============
> The `InAppBrowser` is a web browser that displays in the app when calling `window.open`.
var ref = window.open('http://apache.org', '_blank', 'location=yes');
Description
-----------
The object returned from a call to `window.open`.
Methods
----------
- addEventListener
- removeEventListener
- close
Permissions
-----------
### Android
#### app/res/xml/config.xml
<plugin name="InAppBrowser" value="org.apache.cordova.InAppBrowser" />
### iOS
#### config.xml
<plugin name="InAppBrowser" value="CDVInAppBrowser" />
### Windows Phone 7 + 8
#### config.xml
<plugin name="InAppBrowser" />
addEventListener
================
> Adds a listener for an event from the `InAppBrowser`.
ref.addEventListener(eventname, callback);
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
- __eventname__: the event to listen for _(String)_
- __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.
- __callback__: the function that executes when the event fires. The function is passed an `InAppBrowserEvent` object as a parameter.
Supported Platforms
-------------------
- Android
- iOS
- Windows Phone 7 + 8
Quick Example
-------------
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function() { alert(event.url); });
Full Example
------------
<!DOCTYPE html>
<html>
<head>
<title>InAppBrowser.addEventListener Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
ref.addEventListener('exit', function(event) { alert(event.type); });
}
</script>
</head>
<body>
</body>
</html>
removeEventListener
===================
> Removes a listener for an event from the `InAppBrowser`.
ref.removeEventListener(eventname, callback);
- __ref__: reference to the `InAppBrowser` window. _(InAppBrowser)_
- __eventname__: the event to stop listening for. _(String)_
- __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 loading a URL.
- __exit__: event fires when the `InAppBrowser` window is closed.
- __callback__: the function to execute when the event fires.
The function is passed an `InAppBrowserEvent` object.
Supported Platforms
-------------------
- Android
- iOS
- Windows Phone 7 + 8
Quick Example
-------------
var ref = window.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function() { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
Full Example
------------
<!DOCTYPE html>
<html>
<head>
<title>InAppBrowser.removeEventListener Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Global InAppBrowser reference
var iabRef = null;
function iabLoadStart(event) {
alert(event.type + ' - ' + event.url);
}
function iabLoadStop(event) {
alert(event.type + ' - ' + event.url);
}
function iabLoadError(event) {
alert(event.type + ' - ' + event.message);
}
function iabClose(event) {
alert(event.type);
iabRef.removeEventListener('loadstart', iabLoadStart);
iabRef.removeEventListener('loadstop', iabLoadStop);
iabRef.removeEventListener('loaderror', iabLoadError);
iabRef.removeEventListener('exit', iabClose);
}
// device APIs are available
//
function onDeviceReady() {
iabRef = window.open('http://apache.org', '_blank', 'location=yes');
iabRef.addEventListener('loadstart', iabLoadStart);
iabRef.addEventListener('loadstop', iabLoadStop);
iabRef.removeEventListener('loaderror', iabLoadError);
iabRef.addEventListener('exit', iabClose);
}
</script>
</head>
<body>
</body>
</html>
close
=====
> Closes the `InAppBrowser` window.
ref.close();
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
Supported Platforms
-------------------
- Android
- iOS
- Windows Phone 7 + 8
- BlackBerry 10
Quick Example
-------------
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.close();
Full Example
------------
<!DOCTYPE html>
<html>
<head>
<title>InAppBrowser.close Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var ref = window.open('http://apache.org', '_blank', 'location=yes');
// close InAppBrowser after 5 seconds
setTimeout(function() {
ref.close();
}, 5000);
}
</script>
</head>
<body>
</body>
</html>
executeScript
=============
> Injects JavaScript code into the `InAppBrowser` window
ref.executeScript(details, callback);
- __ref__: reference to the `InAppBrowser` window. _(InAppBrowser)_
- __injectDetails__: details of the script to run, specifying either a `file` or `code` key. _(Object)_
- __file__: URL of the script to inject.
- __code__: Text of the script to inject.
- __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.
Supported Platforms
-------------------
- Android
- iOS
Quick Example
-------------
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeSript({file: "myscript.js"});
});
Full Example
------------
<!DOCTYPE html>
<html>
<head>
<title>InAppBrowser.executeScript Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Global InAppBrowser reference
var iabRef = null;
// Inject our custom JavaScript into the InAppBrowser window
//
function replaceHeaderImage() {
iabRef.executeScript({
code: "var img=document.querySelector('#header img'); img.src='http://cordova.apache.org/images/cordova_bot.png';"
}, function() {
alert("Image Element Successfully Hijacked");
}
}
function iabClose(event) {
iabRef.removeEventListener('loadstop', replaceHeaderImage);
iabRef.removeEventListener('exit', iabClose);
}
// device APIs are available
//
function onDeviceReady() {
iabRef = window.open('http://apache.org', '_blank', 'location=yes');
iabRef.addEventListener('loadstop', replaceHeaderImage);
iabRef.addEventListener('exit', iabClose);
}
</script>
</head>
<body>
</body>
</html>
insertCSS
=========
> Injects CSS into the `InAppBrowser` window.
ref.insertCSS(details, callback);
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
- __injectDetails__: details of the script to run, specifying either a `file` or `code` key. _(Object)_
- __file__: URL of the stylesheet to inject.
- __code__: Text of the stylesheet to inject.
- __callback__: the function that executes after the CSS is injected.
Supported Platforms
-------------------
- Android
- iOS
Quick Example
-------------
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});
Full Example
------------
<!DOCTYPE html>
<html>
<head>
<title>InAppBrowser.executeScript Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Global InAppBrowser reference
var iabRef = null;
// Inject our custom CSS into the InAppBrowser window
//
function changeBackgroundColor() {
iabRef.executeScript({
code: "body { background: #ffff00"
}, function() {
alert("Styles Altered");
}
}
function iabClose(event) {
iabRef.removeEventListener('loadstop', changeBackgroundColor);
iabRef.removeEventListener('exit', iabClose);
}
// device APIs are available
//
function onDeviceReady() {
iabRef = window.open('http://apache.org', '_blank', 'location=yes');
iabRef.addEventListener('loadstop', changeBackgroundColor);
iabRef.addEventListener('exit', iabClose);
}
</script>
</head>
<body>
</body>
</html>
InAppBrowserEvent
=================
The object that is passed to the callback function from an
`addEventListener` call on an `InAppBrowser` object.
Properties
----------
- __type__: the eventname, either `loadstart`, `loadstop`, `loaderror`, or `exit`. _(String)_
- __url__: the URL that was loaded. _(String)_
- __code__: the error code, only in the case of `loaderror`. _(Number)_
- __message__: the error message, only in the case of `loaderror`. _(String)_

View File

@@ -1,100 +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.
---
window.open
===========
Opens a URL in a new `InAppBrowser` instance, the current browser
instance, or the system browser.
var ref = window.open(url, target, options);
- __ref__: Reference to the `InAppBrowser` window. _(InAppBrowser)_
- __url__: The URL to load _(String)_. Call `encodeURI()` on this if the URL contains Unicode characters.
- __target__: The target in which to load the URL, an optional parameter that defaults to `_self`. _(String)_
- `_self`: Opens in the Cordova WebView if the URL is in the white list, otherwise it opens in the `InAppBrowser`.
- `_blank`: Opens in the `InAppBrowser`.
- `_system`: Opens in the system's web 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:
- __location__: Set to `yes` or `no` to turn the `InAppBrowser`'s location bar on or off.
Android only
------------
- __closebuttoncaption__ - set to a string that will be the caption for the "Done" button.
iOS only
--------
- __closebuttoncaption__ - set to a string that will be the caption for the "Done" button. Note that you will have to localize this value yourself.
- __toolbar__ - set to 'yes' or 'no' to turn the toolbar on or off for the InAppBrowser (defaults to 'yes')
- __enableViewportScale__: Set to `yes` or `no` to prevent viewport scaling through a meta tag (defaults to `no`).
- __mediaPlaybackRequiresUserAction__: Set to `yes` or `no` to prevent HTML5 audio or video from autoplaying (defaults to `no`).
- __allowInlineMediaPlayback__: Set to `yes` or `no` to allow inline 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`).
Supported Platforms
-------------------
- Android
- iOS
- BlackBerry 10
- Windows Phone 7 + 8
Quick Example
-------------
var ref = window.open('http://apache.org', '_blank', 'location=yes');
var ref2 = window.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
Full Example
------------
<!DOCTYPE html>
<html>
<head>
<title>window.open Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
// external url
var ref = window.open(encodeURI('http://apache.org'), '_blank', 'location=yes');
// relative document
ref = window.open('next.html', '_self');
}
</script>
</head>
<body>
</body>
</html>

48
package.json Normal file
View File

@@ -0,0 +1,48 @@
{
"name": "cordova-plugin-inappbrowser",
"version": "1.2.1",
"description": "Cordova InAppBrowser Plugin",
"cordova": {
"id": "cordova-plugin-inappbrowser",
"platforms": [
"android",
"amazon-fireos",
"ubuntu",
"ios",
"wp7",
"wp8",
"windows8",
"windows",
"firefoxos"
]
},
"repository": {
"type": "git",
"url": "https://github.com/apache/cordova-plugin-inappbrowser"
},
"keywords": [
"cordova",
"in",
"app",
"browser",
"inappbrowser",
"ecosystem:cordova",
"cordova-android",
"cordova-amazon-fireos",
"cordova-ubuntu",
"cordova-ios",
"cordova-wp7",
"cordova-wp8",
"cordova-windows8",
"cordova-windows",
"cordova-firefoxos"
],
"engines": [
{
"name": "cordova",
"version": ">=3.1.0"
}
],
"author": "Apache Software Foundation",
"license": "Apache 2.0"
}

View File

@@ -1,20 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="org.apache.cordova.inappbrowser"
version="0.2.2">
id="cordova-plugin-inappbrowser"
version="1.2.1">
<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>
<engines>
<engine name="cordova" version=">=3.1.0" /><!-- Needs cordova/urlutil -->
</engines>
<js-module src="www/InAppBrowser.js" name="InAppBrowser">
<clobbers target="window.open" />
</js-module>
<!-- 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">
<param name="android-package" value="org.apache.cordova.inappbrowser.InAppBrowser"/>
@@ -22,11 +46,79 @@
</config-file>
<source-file src="src/android/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/android/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>
<!-- 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">
<platform name="ios">
<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="ios-package" value="CDVInAppBrowser" />
@@ -39,41 +131,97 @@
<framework src="CoreGraphics.framework" />
</platform>
<!-- blackberry10 -->
<!-- <platform name="blackberry10">
<config-file target="www/config.xml" parent="/widget">
<feature name="InAppBrowser" value="InAppBrowser"/>
</config-file>
</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) -->
<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">
<merges target="" />
</js-module>
<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">
<merges target="" />
</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">
<merges target="" />
</js-module>
</platform>
</plugin>

View File

@@ -0,0 +1,846 @@
/*
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 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;
/**
* 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 {
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.
*/
private void goBack() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (InAppBrowser.this.inAppWebView.canGoBack()) {
InAppBrowser.this.inAppWebView.goBack();
}
}
});
}
/**
* 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 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

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

@@ -18,27 +18,16 @@
*/
package org.apache.cordova.inappbrowser;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Dialog;
import org.apache.cordova.inappbrowser.InAppBrowserDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Browser;
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;
@@ -52,11 +41,8 @@ import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.JsPromptResult;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
@@ -64,6 +50,24 @@ 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.CordovaHttpAuthHandler;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginManager;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.StringTokenizer;
@SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
@@ -71,149 +75,195 @@ public class InAppBrowser extends CordovaPlugin {
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 ZOOM = "zoom";
private static final String HIDDEN = "hidden";
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 CLOSE_BUTTON_CAPTION = "closebuttoncaption";
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 Dialog dialog;
private InAppBrowserDialog dialog;
private WebView inAppWebView;
private EditText edittext;
private CallbackContext callbackContext;
private boolean showLocationBar = true;
private boolean showZoomControls = true;
private boolean openWindowHidden = false;
private String buttonLabel = "Done";
private boolean clearAllCache= false;
private boolean clearSessionCache=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.
* @param action the action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext the callbackContext used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if (action.equals("open")) {
this.callbackContext = callbackContext;
String url = args.getString(0);
String target = args.optString(1);
if (target == null || target.equals("") || target.equals(NULL)) {
target = SELF;
}
HashMap<String, Boolean> features = parseFeature(args.optString(2));
Log.d(LOG_TAG, "target = " + target);
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));
url = updateUrl(url);
String result = "";
Log.d(LOG_TAG, "target = " + target);
// SELF
if (SELF.equals(target)) {
Log.d(LOG_TAG, "in self");
// load in webview
if (url.startsWith("file://") || url.startsWith("javascript:")
|| Config.isUrlWhiteListed(url)) {
this.webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.SCHEME_TEL))
{
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
this.cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String result = "";
// SELF
if (SELF.equals(target)) {
Log.d(LOG_TAG, "in self");
/* This code exists for compatibility between 3.x and 4.x versions of Cordova.
* Previously the Config class had a static method, isUrlWhitelisted(). That
* responsibility has been moved to the plugins, with an aggregating method in
* PluginManager.
*/
Boolean shouldAllowNavigation = null;
if (url.startsWith("javascript:")) {
shouldAllowNavigation = true;
}
if (shouldAllowNavigation == null) {
try {
Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
shouldAllowNavigation = (Boolean)iuw.invoke(null, url);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
if (shouldAllowNavigation == null) {
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
PluginManager pm = (PluginManager)gpm.invoke(webView);
Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
shouldAllowNavigation = (Boolean)san.invoke(pm, url);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
// load in webview
if (Boolean.TRUE.equals(shouldAllowNavigation)) {
Log.d(LOG_TAG, "loading in webview");
webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.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);
}
}
// load in InAppBrowser
// SYSTEM
else if (SYSTEM.equals(target)) {
Log.d(LOG_TAG, "in system");
result = openExternal(url);
}
// BLANK - or anything else
else {
result = this.showWebPage(url, features);
Log.d(LOG_TAG, "in blank");
result = showWebPage(url, features);
}
}
// SYSTEM
else if (SYSTEM.equals(target)) {
Log.d(LOG_TAG, "in system");
result = this.openExternal(url);
}
// BLANK - or anything else
else {
Log.d(LOG_TAG, "in blank");
result = this.showWebPage(url, features);
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
else if (action.equals("close")) {
closeDialog();
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
}
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());
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
injectDeferredObject(args.getString(0), jsWrapper);
});
}
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());
}
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("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();
}
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")) {
Runnable runnable = new Runnable() {
@Override
public void run() {
dialog.show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
else {
return false;
}
} catch (JSONException e) {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
});
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 WebView.
*
@@ -241,13 +291,24 @@ public class InAppBrowser extends CordovaPlugin {
} else {
scriptToInject = source;
}
// This action will have the side-effect of blurring the currently focused element
this.inAppWebView.loadUrl("javascript:" + scriptToInject);
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
*/
@@ -262,44 +323,33 @@ public class InAppBrowser extends CordovaPlugin {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
if (key.equalsIgnoreCase(CLOSE_BUTTON_CAPTION)) {
this.buttonLabel = option.nextToken();
} else {
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
}
return map;
}
}
/**
* Convert relative URL to full path
*
* @param url
* @return
*/
private String updateUrl(String url) {
Uri newUrl = Uri.parse(url);
if (newUrl.isRelative()) {
url = this.webView.getUrl().substring(0, this.webView.getUrl().lastIndexOf("/")+1) + url;
}
return url;
}
/**
* 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.
* @param url the url to load.
* @return "" if ok, or error message.
*/
public String openExternal(String url) {
try {
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
// 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);
}
intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName());
this.cordova.getActivity().startActivity(intent);
return "";
} catch (android.content.ActivityNotFoundException e) {
@@ -311,41 +361,67 @@ public class InAppBrowser extends CordovaPlugin {
/**
* Closes the dialog
*/
private void closeDialog() {
try {
final WebView childView = this.inAppWebView;
Runnable runnable = new Runnable() {
@Override
public void run() {
childView.loadUrl("about:blank");
public void closeDialog() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final WebView childView = 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(runnable);
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
if (dialog != null) {
dialog.dismiss();
}
childView.setWebViewClient(new WebViewClient() {
// NB: wait for about:blank before dismissing
public void onPageFinished(WebView view, String url) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
});
// NB: From SDK 19: "If you call methods on WebView from any thread
// other than your app's UI thread, it can cause unexpected results."
// http://developer.android.com/guide/webapps/migrating.html#Threads
childView.loadUrl("about:blank");
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.
*/
private void goBack() {
public void goBack() {
if (this.inAppWebView.canGoBack()) {
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.
*/
@@ -382,25 +458,38 @@ public class InAppBrowser extends CordovaPlugin {
return this.showLocationBar;
}
private InAppBrowser getInAppBrowser(){
return this;
}
/**
* Display a new browser with the specified URL.
*
* @param url The url to load.
* @param jsonObject
* @param url the url to load.
* @param features 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();
@@ -411,7 +500,7 @@ public class InAppBrowser extends CordovaPlugin {
}
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
@@ -430,24 +519,20 @@ public class InAppBrowser extends CordovaPlugin {
return value;
}
@SuppressLint("NewApi")
public void run() {
// CB-6702 InAppBrowser hangs when opening more than one instance
if (dialog != null) {
dialog.dismiss();
};
// Let's create the main dialog
dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
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.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
dialog.setInAppBroswer(getInAppBrowser());
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
@@ -455,7 +540,7 @@ public class InAppBrowser extends CordovaPlugin {
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
//Please, no more black!
//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));
@@ -467,7 +552,7 @@ public class InAppBrowser extends CordovaPlugin {
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(1);
actionButtonContainer.setId(Integer.valueOf(1));
// Back button
Button back = new Button(cordova.getActivity());
@@ -475,8 +560,18 @@ public class InAppBrowser extends CordovaPlugin {
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(2);
back.setText("<");
back.setId(Integer.valueOf(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();
@@ -489,8 +584,17 @@ public class InAppBrowser extends CordovaPlugin {
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(3);
forward.setText(">");
forward.setId(Integer.valueOf(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();
@@ -503,7 +607,7 @@ public class InAppBrowser extends CordovaPlugin {
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(4);
edittext.setId(Integer.valueOf(4));
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
@@ -520,14 +624,23 @@ public class InAppBrowser extends CordovaPlugin {
}
});
// Close button
// 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);
close.setText(buttonLabel);
close.setId(Integer.valueOf(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();
@@ -537,13 +650,14 @@ public class InAppBrowser extends CordovaPlugin {
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(true);
settings.setBuiltInZoomControls(showZoomControls);
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
//Toggle whether this is enabled or not!
@@ -563,7 +677,7 @@ public class InAppBrowser extends CordovaPlugin {
}
inAppWebView.loadUrl(url);
inAppWebView.setId(6);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(true);
inAppWebView.requestFocus();
@@ -598,7 +712,7 @@ public class InAppBrowser extends CordovaPlugin {
// 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();
dialog.hide();
}
}
};
@@ -620,14 +734,18 @@ public class InAppBrowser extends CordovaPlugin {
*
* @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) {
PluginResult result = new PluginResult(status, obj);
result.setKeepCallback(keepCallback);
this.callbackContext.sendPluginResult(result);
*/
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
*/
@@ -638,8 +756,8 @@ public class InAppBrowser extends CordovaPlugin {
/**
* Constructor.
*
* @param mContext
* @param edittext
* @param webView
* @param mEditText
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
this.webView = webView;
@@ -647,34 +765,30 @@ public class InAppBrowser extends CordovaPlugin {
}
/**
* Notify the host application that a page has started loading.
* Override the URL that should be loaded
*
* @param view The webview initiating the callback.
* @param url The url of the page.
* This handles a small subset of all the URIs that would be encountered.
*
* @param webView
* @param url
*/
@Override
public void onPageStarted(WebView 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(WebView.SCHEME_TEL)) {
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
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;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:")) {
} else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
@@ -689,8 +803,7 @@ public class InAppBrowser extends CordovaPlugin {
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
}
else {
} else {
address = url.substring(4, parmIndex);
// If body, then set sms body
@@ -706,58 +819,116 @@ public class InAppBrowser extends CordovaPlugin {
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
else {
return false;
}
/*
* onPageStarted fires the LOAD_START_EVENT
*
* @param view
* @param url
* @param favicon
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc = "";
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
}
else
{
// Assume that everything is HTTP at this point, because if we don't specify,
// it really should be. Complain loudly about this!!!
LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI");
newloc = "http://" + url;
}
// Update the UI if we haven't already
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");
LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
}
}
public void onPageFinished(WebView 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(WebView 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");
}
}
/**
* On received http auth request.
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
// Check if there is some plugin which can resolve this auth challenge
PluginManager pluginManager = null;
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
pluginManager = (PluginManager)gpm.invoke(webView);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
if (pluginManager == null) {
try {
Field pmf = webView.getClass().getField("pluginManager");
pluginManager = (PluginManager)pmf.get(webView);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
}
if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) {
return;
}
// By default handle 401 like we'd normally do!
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
}

View File

@@ -0,0 +1,58 @@
/*
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.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Oliver on 22/11/2013.
*/
public class InAppBrowserDialog extends Dialog {
Context context;
InAppBrowser inAppBrowser = null;
public InAppBrowserDialog(Context context, int theme) {
super(context, theme);
this.context = context;
}
public void setInAppBroswer(InAppBrowser browser) {
this.inAppBrowser = browser;
}
public void onBackPressed () {
if (this.inAppBrowser == null) {
this.dismiss();
} else {
// better to go through the in inAppBrowser
// because it does a clean up
if (this.inAppBrowser.hardwareBack() && this.inAppBrowser.canGoBack()) {
this.inAppBrowser.goBack();
} else {
this.inAppBrowser.closeDialog();
}
}
}
}

View File

@@ -1,3 +1,21 @@
/*
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;
@@ -38,20 +56,7 @@ public class InAppChromeClient extends WebChromeClient {
long totalUsedQuota, WebStorage.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);
}
quotaUpdater.updateQuota(MAX_QUOTA);
}
/**

Binary file not shown.

After

Width:  |  Height:  |  Size: 593 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 599 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 427 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 328 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 727 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 744 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 536 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1021 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 681 B

View File

@@ -1,3 +1,21 @@
<!---
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.

View File

@@ -0,0 +1,24 @@
<!---
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

@@ -0,0 +1,24 @@
<!---
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

@@ -0,0 +1,24 @@
<!---
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

@@ -0,0 +1,24 @@
<!---
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

@@ -0,0 +1,24 @@
<!---
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

@@ -0,0 +1,24 @@
<!---
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

@@ -0,0 +1,24 @@
<!---
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

@@ -0,0 +1,24 @@
<!---
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

@@ -0,0 +1,224 @@
/*
*
* 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.
*
*/
var cordova = require('cordova'),
channel = require('cordova/channel'),
modulemapper = require('cordova/modulemapper'),
urlutil = require('cordova/urlutil');
var browserWrap,
popup,
navigationButtonsDiv,
navigationButtonsDivInner,
backButton,
forwardButton,
closeButton;
function attachNavigationEvents(element, callback) {
var onError = function () {
callback({ type: "loaderror", url: this.contentWindow.location}, {keepCallback: true});
};
element.addEventListener("pageshow", 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("error", onError);
element.addEventListener("abort", onError);
}
var IAB = {
close: function (win, lose) {
if (browserWrap) {
if (win) win({ type: "exit" });
browserWrap.parentNode.removeChild(browserWrap);
browserWrap = null;
popup = null;
}
},
show: function (win, lose) {
if (browserWrap) {
browserWrap.style.display = "block";
}
},
open: function (win, lose, args) {
var strUrl = args[0],
target = args[1],
features = args[2],
url;
if (target === "_self" || !target) {
window.location = strUrl;
} 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.borderWidth = "40px";
browserWrap.style.width = "calc(100% - 80px)";
browserWrap.style.height = "calc(100% - 80px)";
browserWrap.style.borderStyle = "solid";
browserWrap.style.borderColor = "rgba(0,0,0,0.25)";
browserWrap.onclick = function () {
setTimeout(function () {
IAB.close(win);
}, 0);
};
document.body.appendChild(browserWrap);
}
if (features.indexOf("hidden=yes") !== -1) {
browserWrap.style.display = "none";
}
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)";
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.onclick = function (e) {
e.cancelBubble = true;
};
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();
});
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();
});
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) {
setTimeout(function () {
IAB.close(win);
}, 0);
});
// iframe navigation is not yet supported
backButton.disabled = true;
forwardButton.disabled = true;
navigationButtonsDivInner.appendChild(backButton);
navigationButtonsDivInner.appendChild(forwardButton);
navigationButtonsDivInner.appendChild(closeButton);
navigationButtonsDiv.appendChild(navigationButtonsDivInner);
browserWrap.appendChild(navigationButtonsDiv);
} else {
popup.style.height = "100%";
}
// start listening for navigation events
attachNavigationEvents(popup, win);
popup.src = strUrl;
}
},
injectScriptCode: function (win, fail, args) {
var code = args[0],
hasCallback = args[1];
if (browserWrap && popup) {
try {
popup.contentWindow.eval(code);
hasCallback && win([]);
} catch(e) {
console.error('Error occured while trying to injectScriptCode: ' + JSON.stringify(e));
}
}
},
injectScriptFile: function (win, fail, args) {
var msg = 'Browser cordova-plugin-inappbrowser injectScriptFile is not yet implemented';
console.warn(msg);
fail && fail(msg);
},
injectStyleCode: function (win, fail, args) {
var msg = 'Browser cordova-plugin-inappbrowser injectStyleCode is not yet implemented';
console.warn(msg);
fail && fail(msg);
},
injectStyleFile: function (win, fail, args) {
var msg = 'Browser cordova-plugin-inappbrowser injectStyleFile is not yet implemented';
console.warn(msg);
fail && fail(msg);
}
};
module.exports = IAB;
require("cordova/exec/proxy").add("InAppBrowser", module.exports);

View File

@@ -0,0 +1,191 @@
/*
*
* 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 cordova = require('cordova'),
channel = require('cordova/channel'),
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');
},
open: function (win, lose, args) {
var strUrl = args[0],
target = args[1],
features_string = args[2] || "location=yes", //location=yes is default
features = {},
url,
elem;
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');
function checkForwardBackward() {
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

@@ -20,16 +20,21 @@
#import <Cordova/CDVPlugin.h>
#import <Cordova/CDVInvokedUrlCommand.h>
#import <Cordova/CDVScreenOrientationDelegate.h>
#import <Cordova/CDVWebViewDelegate.h>
#ifdef __CORDOVA_4_0_0
#import <Cordova/CDVUIWebViewDelegate.h>
#else
#import <Cordova/CDVWebViewDelegate.h>
#endif
@class CDVInAppBrowserViewController;
@interface CDVInAppBrowser : CDVPlugin {
BOOL _injectedIframeBridge;
}
@property (nonatomic, retain) CDVInAppBrowserViewController* inAppBrowserViewController;
@property (nonatomic, copy) NSString* callbackId;
@property (nonatomic, copy) NSRegularExpression *callbackIdPattern;
- (void)open:(CDVInvokedUrlCommand*)command;
- (void)close:(CDVInvokedUrlCommand*)command;
@@ -38,12 +43,43 @@
@end
@interface CDVInAppBrowserViewController : UIViewController <UIWebViewDelegate>{
@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;
@@ -61,29 +97,16 @@
- (void)close;
- (void)navigateTo:(NSURL*)url;
- (void)showLocationBar:(BOOL)show;
- (void)showToolBar:(BOOL)show;
- (void)showToolBar:(BOOL)show : (NSString *) toolbarPosition;
- (void)setCloseButtonTitle:(NSString*)title;
- (id)initWithUserAgent:(NSString*)userAgent prevUserAgent:(NSString*)prevUserAgent;
- (id)initWithUserAgent:(NSString*)userAgent prevUserAgent:(NSString*)prevUserAgent browserOptions: (CDVInAppBrowserOptions*) browserOptions;
@end
@interface CDVInAppBrowserOptions : NSObject {}
@interface CDVInAppBrowserNavigationController : UINavigationController
@property (nonatomic, assign) BOOL location;
@property (nonatomic, assign) BOOL toolbar;
@property (nonatomic, copy) NSString* closebuttoncaption;
@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;
+ (CDVInAppBrowserOptions*)parseOptions:(NSString*)options;
@property (nonatomic, weak) id <CDVScreenOrientationDelegate> orientationDelegate;
@end

View File

@@ -20,28 +20,31 @@
#import "CDVInAppBrowser.h"
#import <Cordova/CDVPluginResult.h>
#import <Cordova/CDVUserAgentUtil.h>
#import <Cordova/CDVJSON.h>
#define kInAppBrowserTargetSelf @"_self"
#define kInAppBrowserTargetSystem @"_system"
#define kInAppBrowserTargetBlank @"_blank"
#define kInAppBrowserToolbarBarPositionBottom @"bottom"
#define kInAppBrowserToolbarBarPositionTop @"top"
#define TOOLBAR_HEIGHT 44.0
#define LOCATIONBAR_HEIGHT 21.0
#define FOOTER_HEIGHT ((TOOLBAR_HEIGHT) + (LOCATIONBAR_HEIGHT))
#pragma mark CDVInAppBrowser
@interface CDVInAppBrowser () {
NSInteger _previousStatusBarStyle;
}
@end
@implementation CDVInAppBrowser
- (CDVInAppBrowser*)initWithWebView:(UIWebView*)theWebView
- (void)pluginInitialize
{
self = [super initWithWebView:theWebView];
if (self != nil) {
// your initialization here
}
return self;
_previousStatusBarStyle = -1;
_callbackIdPattern = nil;
}
- (void)onReset
@@ -51,12 +54,12 @@
- (void)close:(CDVInvokedUrlCommand*)command
{
if (self.inAppBrowserViewController != nil) {
[self.inAppBrowserViewController close];
self.inAppBrowserViewController = nil;
if (self.inAppBrowserViewController == nil) {
NSLog(@"IAB.close() called but it was already closed.");
return;
}
self.callbackId = nil;
// Things are cleaned up in browserExit.
[self.inAppBrowserViewController close];
}
- (BOOL) isSystemUrl:(NSURL*)url
@@ -64,7 +67,7 @@
if ([[url host] isEqualToString:@"itunes.apple.com"]) {
return YES;
}
return NO;
}
@@ -79,9 +82,13 @@
self.callbackId = command.callbackId;
if (url != nil) {
#ifdef __CORDOVA_4_0_0
NSURL* baseUrl = [self.webViewEngine URL];
#else
NSURL* baseUrl = [self.webView.request URL];
#endif
NSURL* absoluteUrl = [[NSURL URLWithString:url relativeToURL:baseUrl] absoluteURL];
if ([self isSystemUrl:absoluteUrl]) {
target = kInAppBrowserTargetSystem;
}
@@ -105,9 +112,33 @@
- (void)openInInAppBrowser:(NSURL*)url withOptions:(NSString*)options
{
CDVInAppBrowserOptions* browserOptions = [CDVInAppBrowserOptions parseOptions:options];
if (browserOptions.clearcache) {
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
if (![cookie.domain isEqual: @".^filecookies^"]) {
[storage deleteCookie:cookie];
}
}
}
if (browserOptions.clearsessioncache) {
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
if (![cookie.domain isEqual: @".^filecookies^"] && cookie.isSessionOnly) {
[storage deleteCookie:cookie];
}
}
}
if (self.inAppBrowserViewController == nil) {
NSString* originalUA = [CDVUserAgentUtil originalUserAgent];
self.inAppBrowserViewController = [[CDVInAppBrowserViewController alloc] initWithUserAgent:originalUA prevUserAgent:[self.commandDelegate userAgent]];
self.inAppBrowserViewController = [[CDVInAppBrowserViewController alloc] initWithUserAgent:originalUA prevUserAgent:[self.commandDelegate userAgent] browserOptions: browserOptions];
self.inAppBrowserViewController.navigationDelegate = self;
if ([self.viewController conformsToProtocol:@protocol(CDVScreenOrientationDelegate)]) {
@@ -115,10 +146,8 @@
}
}
CDVInAppBrowserOptions* browserOptions = [CDVInAppBrowserOptions parseOptions:options];
[self.inAppBrowserViewController showLocationBar:browserOptions.location];
[self.inAppBrowserViewController showToolBar:browserOptions.toolbar];
[self.inAppBrowserViewController showToolBar:browserOptions.toolbar :browserOptions.toolbarposition];
if (browserOptions.closebuttoncaption != nil) {
[self.inAppBrowserViewController setCloseButtonTitle:browserOptions.closebuttoncaption];
}
@@ -144,7 +173,19 @@
}
self.inAppBrowserViewController.modalTransitionStyle = transitionStyle;
// prevent webView from bouncing
if (browserOptions.disallowoverscroll) {
if ([self.inAppBrowserViewController.webView respondsToSelector:@selector(scrollView)]) {
((UIScrollView*)[self.inAppBrowserViewController.webView scrollView]).bounces = NO;
} else {
for (id subview in self.inAppBrowserViewController.webView.subviews) {
if ([[subview class] isSubclassOfClass:[UIScrollView class]]) {
((UIScrollView*)subview).bounces = NO;
}
}
}
}
// UIWebView options
self.inAppBrowserViewController.webView.scalesPageToFit = browserOptions.enableviewportscale;
self.inAppBrowserViewController.webView.mediaPlaybackRequiresUserAction = browserOptions.mediaplaybackrequiresuseraction;
@@ -153,30 +194,56 @@
self.inAppBrowserViewController.webView.keyboardDisplayRequiresUserAction = browserOptions.keyboarddisplayrequiresuseraction;
self.inAppBrowserViewController.webView.suppressesIncrementalRendering = browserOptions.suppressesincrementalrendering;
}
if (! browserOptions.hidden) {
if (self.viewController.modalViewController != self.inAppBrowserViewController) {
[self.viewController presentModalViewController:self.inAppBrowserViewController animated:YES];
}
}
[self.inAppBrowserViewController navigateTo:url];
if (!browserOptions.hidden) {
[self show:nil];
}
}
- (void)show:(CDVInvokedUrlCommand*)command
{
if ([self.inAppBrowserViewController isViewLoaded] && self.inAppBrowserViewController.view.window)
if (self.inAppBrowserViewController == nil) {
NSLog(@"Tried to show IAB after it was closed.");
return;
[self.viewController presentModalViewController:self.inAppBrowserViewController animated:YES];
}
if (_previousStatusBarStyle != -1) {
NSLog(@"Tried to show IAB while already shown");
return;
}
_previousStatusBarStyle = [UIApplication sharedApplication].statusBarStyle;
__block CDVInAppBrowserNavigationController* nav = [[CDVInAppBrowserNavigationController alloc]
initWithRootViewController:self.inAppBrowserViewController];
nav.orientationDelegate = self.inAppBrowserViewController;
nav.navigationBarHidden = YES;
__weak CDVInAppBrowser* weakSelf = self;
// Run later to avoid the "took a long time" log message.
dispatch_async(dispatch_get_main_queue(), ^{
if (weakSelf.inAppBrowserViewController != nil) {
[weakSelf.viewController presentViewController:nav animated:YES completion:nil];
}
});
}
- (void)openInCordovaWebView:(NSURL*)url withOptions:(NSString*)options
{
NSURLRequest* request = [NSURLRequest requestWithURL:url];
#ifdef __CORDOVA_4_0_0
// the webview engine itself will filter for this according to <allow-navigation> policy
// in config.xml for cordova-ios-4.0
[self.webViewEngine loadRequest:request];
#else
if ([self.commandDelegate URLIsWhitelisted:url]) {
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
} else { // this assumes the InAppBrowser can be excepted from the white-list
[self openInInAppBrowser:url withOptions:options];
}
#endif
}
- (void)openInSystem:(NSURL*)url
@@ -199,14 +266,12 @@
- (void)injectDeferredObject:(NSString*)source withWrapper:(NSString*)jsWrapper
{
if (!_injectedIframeBridge) {
_injectedIframeBridge = YES;
// Create an iframe bridge in the new document to communicate with the CDVInAppBrowserViewController
[self.inAppBrowserViewController.webView stringByEvaluatingJavaScriptFromString:@"(function(d){var e = _cdvIframeBridge = d.createElement('iframe');e.style.display='none';d.body.appendChild(e);})(document)"];
}
// Ensure an iframe bridge is created to communicate with the CDVInAppBrowserViewController
[self.inAppBrowserViewController.webView stringByEvaluatingJavaScriptFromString:@"(function(d){_cdvIframeBridge=d.getElementById('_cdvIframeBridge');if(!_cdvIframeBridge) {var e = _cdvIframeBridge = d.createElement('iframe');e.id='_cdvIframeBridge'; e.style.display='none';d.body.appendChild(e);}})(document)"];
if (jsWrapper != nil) {
NSString* sourceArrayString = [@[source] JSONString];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:@[source] options:0 error:nil];
NSString* sourceArrayString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (sourceArrayString) {
NSString* sourceString = [sourceArrayString substringWithRange:NSMakeRange(1, [sourceArrayString length] - 2)];
NSString* jsToInject = [NSString stringWithFormat:jsWrapper, sourceString];
@@ -222,7 +287,7 @@
NSString* jsWrapper = nil;
if ((command.callbackId != nil) && ![command.callbackId isEqualToString:@"INVALID"]) {
jsWrapper = [NSString stringWithFormat:@"_cdvIframeBridge.src='gap-iab://%@/'+window.escape(JSON.stringify([eval(%%@)]));", command.callbackId];
jsWrapper = [NSString stringWithFormat:@"_cdvIframeBridge.src='gap-iab://%@/'+encodeURIComponent(JSON.stringify([eval(%%@)]));", command.callbackId];
}
[self injectDeferredObject:[command argumentAtIndex:0] withWrapper:jsWrapper];
}
@@ -263,6 +328,23 @@
[self injectDeferredObject:[command argumentAtIndex:0] withWrapper:jsWrapper];
}
- (BOOL)isValidCallbackId:(NSString *)callbackId
{
NSError *err = nil;
// Initialize on first use
if (self.callbackIdPattern == nil) {
self.callbackIdPattern = [NSRegularExpression regularExpressionWithPattern:@"^InAppBrowser[0-9]{1,10}$" options:0 error:&err];
if (err != nil) {
// Couldn't initialize Regex; No is safer than Yes.
return NO;
}
}
if ([self.callbackIdPattern firstMatchInString:callbackId options:0 range:NSMakeRange(0, [callbackId length])]) {
return YES;
}
return NO;
}
/**
* The iframe 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
@@ -289,7 +371,7 @@
NSString* scriptCallbackId = [url host];
CDVPluginResult* pluginResult = nil;
if ([scriptCallbackId hasPrefix:@"InAppBrowser"]) {
if ([self isValidCallbackId:scriptCallbackId]) {
NSString* scriptResult = [url path];
NSError* __autoreleasing error = nil;
@@ -308,7 +390,14 @@
[self.commandDelegate sendPluginResult:pluginResult callbackId:scriptCallbackId];
return NO;
}
} else if ((self.callbackId != nil) && isTopLevelNavigation) {
}
//if is an app store link, let the system handle it, otherwise it fails to load it
else if ([[ url scheme] isEqualToString:@"itms-appss"] || [[ url scheme] isEqualToString:@"itms-apps"]) {
[theWebView stopLoading];
[self openInSystem:url];
return NO;
}
else if ((self.callbackId != nil) && isTopLevelNavigation) {
// Send a loadstart event for each top-level navigation (includes redirects).
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsDictionary:@{@"type":@"loadstart", @"url":[url absoluteString]}];
@@ -322,7 +411,6 @@
- (void)webViewDidStartLoad:(UIWebView*)theWebView
{
_injectedIframeBridge = NO;
}
- (void)webViewDidFinishLoad:(UIWebView*)theWebView
@@ -343,7 +431,7 @@
if (self.callbackId != nil) {
NSString* url = [self.inAppBrowserViewController.currentURL absoluteString];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
messageAsDictionary:@{@"type":@"loaderror", @"url":url, @"code": [NSNumber numberWithInt:error.code], @"message": error.localizedDescription}];
messageAsDictionary:@{@"type":@"loaderror", @"url":url, @"code": [NSNumber numberWithInteger:error.code], @"message": error.localizedDescription}];
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
@@ -355,13 +443,22 @@
if (self.callbackId != nil) {
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsDictionary:@{@"type":@"exit"}];
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
self.callbackId = nil;
}
// Set navigationDelegate to nil to ensure no callbacks are received from it.
self.inAppBrowserViewController.navigationDelegate = nil;
// Don't recycle the ViewController since it may be consuming a lot of memory.
// Also - this is required for the PDF/User-Agent bug work-around.
self.inAppBrowserViewController = nil;
if (IsAtLeastiOSVersion(@"7.0")) {
if (_previousStatusBarStyle != -1) {
[[UIApplication sharedApplication] setStatusBarStyle:_previousStatusBarStyle];
}
}
_previousStatusBarStyle = -1; // this value was reset before reapplying it. caused statusbar to stay black on ios7
}
@end
@@ -372,28 +469,39 @@
@synthesize currentURL;
- (id)initWithUserAgent:(NSString*)userAgent prevUserAgent:(NSString*)prevUserAgent
- (id)initWithUserAgent:(NSString*)userAgent prevUserAgent:(NSString*)prevUserAgent browserOptions: (CDVInAppBrowserOptions*) browserOptions
{
self = [super init];
if (self != nil) {
_userAgent = userAgent;
_prevUserAgent = prevUserAgent;
_browserOptions = browserOptions;
#ifdef __CORDOVA_4_0_0
_webViewDelegate = [[CDVUIWebViewDelegate alloc] initWithDelegate:self];
#else
_webViewDelegate = [[CDVWebViewDelegate alloc] initWithDelegate:self];
#endif
[self createViews];
}
return self;
}
// Prevent crashes on closing windows
-(void)dealloc {
self.webView.delegate = nil;
}
- (void)createViews
{
// We create the views in code for primarily for ease of upgrades and not requiring an external .xib to be included
CGRect webViewBounds = self.view.bounds;
webViewBounds.size.height -= FOOTER_HEIGHT;
BOOL toolbarIsAtBottom = ![_browserOptions.toolbarposition isEqualToString:kInAppBrowserToolbarBarPositionTop];
webViewBounds.size.height -= _browserOptions.location ? FOOTER_HEIGHT : TOOLBAR_HEIGHT;
self.webView = [[UIWebView alloc] initWithFrame:webViewBounds];
self.webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
[self.view addSubview:self.webView];
@@ -405,22 +513,20 @@
self.webView.clearsContextBeforeDrawing = YES;
self.webView.clipsToBounds = YES;
self.webView.contentMode = UIViewContentModeScaleToFill;
self.webView.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
self.webView.multipleTouchEnabled = YES;
self.webView.opaque = YES;
self.webView.scalesPageToFit = NO;
self.webView.userInteractionEnabled = YES;
self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.spinner.alpha = 1.000;
self.spinner.autoresizesSubviews = YES;
self.spinner.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
self.spinner.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin);
self.spinner.clearsContextBeforeDrawing = NO;
self.spinner.clipsToBounds = NO;
self.spinner.contentMode = UIViewContentModeScaleToFill;
self.spinner.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
self.spinner.frame = CGRectMake(454.0, 231.0, 20.0, 20.0);
self.spinner.hidden = YES;
self.spinner.frame = CGRectMake(CGRectGetMidX(self.webView.frame), CGRectGetMidY(self.webView.frame), 20.0, 20.0);
self.spinner.hidden = NO;
self.spinner.hidesWhenStopped = YES;
self.spinner.multipleTouchEnabled = NO;
self.spinner.opaque = NO;
@@ -435,22 +541,26 @@
UIBarButtonItem* fixedSpaceButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
fixedSpaceButton.width = 20;
self.toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0, (self.view.bounds.size.height - TOOLBAR_HEIGHT), self.view.bounds.size.width, TOOLBAR_HEIGHT)];
float toolbarY = toolbarIsAtBottom ? self.view.bounds.size.height - TOOLBAR_HEIGHT : 0.0;
CGRect toolbarFrame = CGRectMake(0.0, toolbarY, self.view.bounds.size.width, TOOLBAR_HEIGHT);
self.toolbar = [[UIToolbar alloc] initWithFrame:toolbarFrame];
self.toolbar.alpha = 1.000;
self.toolbar.autoresizesSubviews = YES;
self.toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
self.toolbar.autoresizingMask = toolbarIsAtBottom ? (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin) : UIViewAutoresizingFlexibleWidth;
self.toolbar.barStyle = UIBarStyleBlackOpaque;
self.toolbar.clearsContextBeforeDrawing = NO;
self.toolbar.clipsToBounds = NO;
self.toolbar.contentMode = UIViewContentModeScaleToFill;
self.toolbar.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
self.toolbar.hidden = NO;
self.toolbar.multipleTouchEnabled = NO;
self.toolbar.opaque = NO;
self.toolbar.userInteractionEnabled = YES;
CGFloat labelInset = 5.0;
self.addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(labelInset, (self.view.bounds.size.height - FOOTER_HEIGHT), self.view.bounds.size.width - labelInset, LOCATIONBAR_HEIGHT)];
float locationBarY = toolbarIsAtBottom ? self.view.bounds.size.height - FOOTER_HEIGHT : self.view.bounds.size.height - LOCATIONBAR_HEIGHT;
self.addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(labelInset, locationBarY, self.view.bounds.size.width - labelInset, LOCATIONBAR_HEIGHT)];
self.addressLabel.adjustsFontSizeToFitWidth = NO;
self.addressLabel.alpha = 1.000;
self.addressLabel.autoresizesSubviews = YES;
@@ -460,26 +570,31 @@
self.addressLabel.clearsContextBeforeDrawing = YES;
self.addressLabel.clipsToBounds = YES;
self.addressLabel.contentMode = UIViewContentModeScaleToFill;
self.addressLabel.contentStretch = CGRectFromString(@"{{0, 0}, {1, 1}}");
self.addressLabel.enabled = YES;
self.addressLabel.hidden = NO;
self.addressLabel.lineBreakMode = UILineBreakModeTailTruncation;
self.addressLabel.minimumFontSize = 10.000;
self.addressLabel.lineBreakMode = NSLineBreakByTruncatingTail;
if ([self.addressLabel respondsToSelector:NSSelectorFromString(@"setMinimumScaleFactor:")]) {
[self.addressLabel setValue:@(10.0/[UIFont labelFontSize]) forKey:@"minimumScaleFactor"];
} else if ([self.addressLabel respondsToSelector:NSSelectorFromString(@"setMinimumFontSize:")]) {
[self.addressLabel setValue:@(10.0) forKey:@"minimumFontSize"];
}
self.addressLabel.multipleTouchEnabled = NO;
self.addressLabel.numberOfLines = 1;
self.addressLabel.opaque = NO;
self.addressLabel.shadowOffset = CGSizeMake(0.0, -1.0);
self.addressLabel.text = @"Loading...";
self.addressLabel.textAlignment = UITextAlignmentLeft;
self.addressLabel.text = NSLocalizedString(@"Loading...", nil);
self.addressLabel.textAlignment = NSTextAlignmentLeft;
self.addressLabel.textColor = [UIColor colorWithWhite:1.000 alpha:1.000];
self.addressLabel.userInteractionEnabled = NO;
NSString* frontArrowString = @"►"; // create arrow from Unicode char
NSString* frontArrowString = NSLocalizedString(@"►", nil); // create arrow from Unicode char
self.forwardButton = [[UIBarButtonItem alloc] initWithTitle:frontArrowString style:UIBarButtonItemStylePlain target:self action:@selector(goForward:)];
self.forwardButton.enabled = YES;
self.forwardButton.imageInsets = UIEdgeInsetsZero;
NSString* backArrowString = @"◄"; // create arrow from Unicode char
NSString* backArrowString = NSLocalizedString(@"◄", nil); // create arrow from Unicode char
self.backButton = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStylePlain target:self action:@selector(goBack:)];
self.backButton.enabled = YES;
self.backButton.imageInsets = UIEdgeInsetsZero;
@@ -492,6 +607,11 @@
[self.view addSubview:self.spinner];
}
- (void) setWebViewFrame : (CGRect) frame {
NSLog(@"Setting the WebView's frame to %@", NSStringFromCGRect(frame));
[self.webView setFrame:frame];
}
- (void)setCloseButtonTitle:(NSString*)title
{
// the advantage of using UIBarButtonSystemItemDone is the system will localize it for you automatically
@@ -526,7 +646,7 @@
CGRect webViewBounds = self.view.bounds;
webViewBounds.size.height -= FOOTER_HEIGHT;
self.webView.frame = webViewBounds;
[self setWebViewFrame:webViewBounds];
locationbarFrame.origin.y = webViewBounds.size.height;
self.addressLabel.frame = locationbarFrame;
@@ -535,7 +655,7 @@
CGRect webViewBounds = self.view.bounds;
webViewBounds.size.height -= LOCATIONBAR_HEIGHT;
self.webView.frame = webViewBounds;
[self setWebViewFrame:webViewBounds];
locationbarFrame.origin.y = webViewBounds.size.height;
self.addressLabel.frame = locationbarFrame;
@@ -549,17 +669,15 @@
// webView take up whole height less toolBar height
CGRect webViewBounds = self.view.bounds;
webViewBounds.size.height -= TOOLBAR_HEIGHT;
self.webView.frame = webViewBounds;
[self setWebViewFrame:webViewBounds];
} else {
// no toolBar, expand webView to screen dimensions
CGRect webViewBounds = self.view.bounds;
self.webView.frame = webViewBounds;
[self setWebViewFrame:self.view.bounds];
}
}
}
- (void)showToolBar:(BOOL)show
- (void)showToolBar:(BOOL)show : (NSString *) toolbarPosition
{
CGRect toolbarFrame = self.toolbar.frame;
CGRect locationbarFrame = self.addressLabel.frame;
@@ -573,30 +691,31 @@
if (show) {
self.toolbar.hidden = NO;
CGRect webViewBounds = self.view.bounds;
if (locationbarVisible) {
// locationBar at the bottom, move locationBar up
// put toolBar at the bottom
CGRect webViewBounds = self.view.bounds;
webViewBounds.size.height -= FOOTER_HEIGHT;
self.webView.frame = webViewBounds;
locationbarFrame.origin.y = webViewBounds.size.height;
self.addressLabel.frame = locationbarFrame;
toolbarFrame.origin.y = (webViewBounds.size.height + LOCATIONBAR_HEIGHT);
self.toolbar.frame = toolbarFrame;
} else {
// no locationBar, so put toolBar at the bottom
CGRect webViewBounds = self.view.bounds;
webViewBounds.size.height -= TOOLBAR_HEIGHT;
self.webView.frame = webViewBounds;
toolbarFrame.origin.y = webViewBounds.size.height;
self.toolbar.frame = toolbarFrame;
}
if ([toolbarPosition isEqualToString:kInAppBrowserToolbarBarPositionTop]) {
toolbarFrame.origin.y = 0;
webViewBounds.origin.y += toolbarFrame.size.height;
[self setWebViewFrame:webViewBounds];
} else {
toolbarFrame.origin.y = (webViewBounds.size.height + LOCATIONBAR_HEIGHT);
}
[self setWebViewFrame:webViewBounds];
} else {
self.toolbar.hidden = YES;
@@ -607,16 +726,14 @@
// webView take up whole height less locationBar height
CGRect webViewBounds = self.view.bounds;
webViewBounds.size.height -= LOCATIONBAR_HEIGHT;
self.webView.frame = webViewBounds;
[self setWebViewFrame:webViewBounds];
// move locationBar down
locationbarFrame.origin.y = webViewBounds.size.height;
self.addressLabel.frame = locationbarFrame;
} else {
// no locationBar, expand webView to screen dimensions
CGRect webViewBounds = self.view.bounds;
self.webView.frame = webViewBounds;
[self setWebViewFrame:self.view.bounds];
}
}
}
@@ -633,21 +750,30 @@
[super viewDidUnload];
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleDefault;
}
- (void)close
{
[CDVUserAgentUtil releaseLock:&_userAgentLockToken];
if ([self respondsToSelector:@selector(presentingViewController)]) {
[[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
} else {
[[self parentViewController] dismissModalViewControllerAnimated:YES];
}
self.currentURL = nil;
if ((self.navigationDelegate != nil) && [self.navigationDelegate respondsToSelector:@selector(browserExit)]) {
[self.navigationDelegate browserExit];
}
__weak UIViewController* weakSelf = self;
// Run later to avoid the "took a long time" log message.
dispatch_async(dispatch_get_main_queue(), ^{
if ([weakSelf respondsToSelector:@selector(presentingViewController)]) {
[[weakSelf presentingViewController] dismissViewControllerAnimated:YES completion:nil];
} else {
[[weakSelf parentViewController] dismissViewControllerAnimated:YES completion:nil];
}
});
}
- (void)navigateTo:(NSURL*)url
@@ -657,10 +783,11 @@
if (_userAgentLockToken != 0) {
[self.webView loadRequest:request];
} else {
__weak CDVInAppBrowserViewController* weakSelf = self;
[CDVUserAgentUtil acquireLock:^(NSInteger lockToken) {
_userAgentLockToken = lockToken;
[CDVUserAgentUtil setUserAgent:_userAgent lockToken:lockToken];
[self.webView loadRequest:request];
[weakSelf.webView loadRequest:request];
}];
}
}
@@ -675,13 +802,41 @@
[self.webView goForward];
}
- (void)viewWillAppear:(BOOL)animated
{
if (IsAtLeastiOSVersion(@"7.0")) {
[[UIApplication sharedApplication] setStatusBarStyle:[self preferredStatusBarStyle]];
}
[self rePositionViews];
[super viewWillAppear:animated];
}
//
// On iOS 7 the status bar is part of the view's dimensions, therefore it's height has to be taken into account.
// The height of it could be hardcoded as 20 pixels, but that would assume that the upcoming releases of iOS won't
// change that value.
//
- (float) getStatusBarOffset {
CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
float statusBarOffset = IsAtLeastiOSVersion(@"7.0") ? MIN(statusBarFrame.size.width, statusBarFrame.size.height) : 0.0;
return statusBarOffset;
}
- (void) rePositionViews {
if ([_browserOptions.toolbarposition isEqualToString:kInAppBrowserToolbarBarPositionTop]) {
[self.webView setFrame:CGRectMake(self.webView.frame.origin.x, TOOLBAR_HEIGHT, self.webView.frame.size.width, self.webView.frame.size.height)];
[self.toolbar setFrame:CGRectMake(self.toolbar.frame.origin.x, [self getStatusBarOffset], self.toolbar.frame.size.width, self.toolbar.frame.size.height)];
}
}
#pragma mark UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView*)theWebView
{
// loading url, start spinner, update back/forward
self.addressLabel.text = @"Loading...";
self.addressLabel.text = NSLocalizedString(@"Loading...", nil);
self.backButton.enabled = theWebView.canGoBack;
self.forwardButton.enabled = theWebView.canGoForward;
@@ -732,13 +887,13 @@
- (void)webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error
{
// log fail message, stop spinner, update back/forward
NSLog(@"webView:didFailLoadWithError - %@", [error localizedDescription]);
NSLog(@"webView:didFailLoadWithError - %ld: %@", (long)error.code, [error localizedDescription]);
self.backButton.enabled = theWebView.canGoBack;
self.forwardButton.enabled = theWebView.canGoForward;
[self.spinner stopAnimating];
self.addressLabel.text = @"Load Error";
self.addressLabel.text = NSLocalizedString(@"Load Error", nil);
[self.navigationDelegate webView:theWebView didFailLoadWithError:error];
}
@@ -782,6 +937,9 @@
self.location = YES;
self.toolbar = YES;
self.closebuttoncaption = nil;
self.toolbarposition = kInAppBrowserToolbarBarPositionBottom;
self.clearcache = NO;
self.clearsessioncache = NO;
self.enableviewportscale = NO;
self.mediaplaybackrequiresuseraction = NO;
@@ -789,6 +947,7 @@
self.keyboarddisplayrequiresuseraction = YES;
self.suppressesincrementalrendering = NO;
self.hidden = NO;
self.disallowoverscroll = NO;
}
return self;
@@ -832,3 +991,51 @@
}
@end
@implementation CDVInAppBrowserNavigationController : UINavigationController
- (void) viewDidLoad {
CGRect frame = [UIApplication sharedApplication].statusBarFrame;
// simplified from: http://stackoverflow.com/a/25669695/219684
UIToolbar* bgToolbar = [[UIToolbar alloc] initWithFrame:frame];
bgToolbar.barStyle = UIBarStyleDefault;
[self.view addSubview:bgToolbar];
[super viewDidLoad];
}
#pragma mark CDVScreenOrientationDelegate
- (BOOL)shouldAutorotate
{
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(shouldAutorotate)]) {
return [self.orientationDelegate shouldAutorotate];
}
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(supportedInterfaceOrientations)]) {
return [self.orientationDelegate supportedInterfaceOrientations];
}
return 1 << UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(shouldAutorotateToInterfaceOrientation:)]) {
return [self.orientationDelegate shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}
return YES;
}
@end

View File

@@ -0,0 +1,92 @@
/*
*
* 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

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

BIN
src/ubuntu/close.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 461 B

105
src/ubuntu/inappbrowser.cpp Normal file
View File

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

61
src/ubuntu/inappbrowser.h Normal file
View File

@@ -0,0 +1,61 @@
/*
*
* 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 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

@@ -0,0 +1,340 @@
/*
*
* 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 cordova = require('cordova'),
urlutil = require('cordova/urlutil');
var browserWrap,
popup,
navigationButtonsDiv,
navigationButtonsDivInner,
backButton,
forwardButton,
closeButton,
bodyOverflowStyle,
navigationEventsCallback;
// x-ms-webview is available starting from Windows 8.1 (platformId is 'windows')
// http://msdn.microsoft.com/en-us/library/windows/apps/dn301831.aspx
var isWebViewAvailable = cordova.platformId === 'windows';
function attachNavigationEvents(element, callback) {
if (isWebViewAvailable) {
element.addEventListener("MSWebViewNavigationStarting", function (e) {
callback({ type: "loadstart", url: e.uri}, {keepCallback: true} );
});
element.addEventListener("MSWebViewNavigationCompleted", function (e) {
if (e.isSuccess) {
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 });
}
});
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 });
});
element.addEventListener("MSWebViewContentLoading", function (e) {
if (navigationButtonsDiv && popup) {
if (popup.canGoBack) {
backButton.removeAttribute("disabled");
} else {
backButton.setAttribute("disabled", "true");
}
if (popup.canGoForward) {
forwardButton.removeAttribute("disabled");
} else {
forwardButton.setAttribute("disabled", "true");
}
}
});
} else {
var onError = function () {
callback({ type: "loaderror", 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("error", onError);
element.addEventListener("abort", onError);
}
}
var IAB = {
close: function (win, lose) {
setImmediate(function () {
if (browserWrap) {
if (navigationEventsCallback) {
navigationEventsCallback({ type: "exit" });
}
browserWrap.parentNode.removeChild(browserWrap);
// Reset body overflow style to initial value
document.body.style.msOverflowStyle = bodyOverflowStyle;
browserWrap = null;
popup = null;
}
});
},
show: function (win, lose) {
setImmediate(function () {
if (browserWrap) {
browserWrap.style.display = "block";
}
});
},
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;
navigationEventsCallback = win;
if (target === "_system") {
url = new Windows.Foundation.Uri(strUrl);
Windows.System.Launcher.launchUriAsync(url);
} 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");
document.head.appendChild(browserWrapStyle);
browserWrap = document.createElement("div");
browserWrap.className = "inAppBrowserWrap";
if (features.indexOf("fullscreen=yes") > -1) {
browserWrap.classList.add("inAppBrowserWrapFullscreen");
}
// Save body overflow style to be able to reset it back later
bodyOverflowStyle = document.body.style.msOverflowStyle;
browserWrap.onclick = function () {
setTimeout(function () {
IAB.close(navigationEventsCallback);
}, 0);
};
document.body.appendChild(browserWrap);
// Hide scrollbars for the whole body while inappbrowser's window is open
document.body.style.msOverflowStyle = "none";
}
if (features.indexOf("hidden=yes") !== -1) {
browserWrap.style.display = "none";
}
popup = document.createElement(isWebViewAvailable ? "x-ms-webview" : "iframe");
if (popup instanceof HTMLIFrameElement) {
// 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.borderWidth = "0px";
popup.style.width = "100%";
browserWrap.appendChild(popup);
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.onclick = function (e) {
e.cancelBubble = true;
};
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();
});
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", function (e) {
setTimeout(function () {
IAB.close(navigationEventsCallback);
}, 0);
});
if (!isWebViewAvailable) {
// iframe navigation is not yet supported
backButton.setAttribute("disabled", "true");
forwardButton.setAttribute("disabled", "true");
}
navigationButtonsDivInner.appendChild(backButton);
navigationButtonsDivInner.appendChild(forwardButton);
navigationButtonsDivInner.appendChild(closeButton);
navigationButtonsDiv.appendChild(navigationButtonsDivInner);
browserWrap.appendChild(navigationButtonsDiv);
} else {
popup.style.height = "100%";
}
// start listening for navigation events
attachNavigationEvents(popup, navigationEventsCallback);
if (isWebViewAvailable) {
strUrl = strUrl.replace("ms-appx://", "ms-appx-web://");
}
popup.src = strUrl;
}
});
},
injectScriptCode: function (win, fail, args) {
setImmediate(function () {
var code = args[0],
hasCallback = args[1];
if (isWebViewAvailable && browserWrap && popup) {
var op = popup.invokeScriptAsync("eval", code);
op.oncomplete = function (e) {
// return null if event target is unavailable by some reason
var result = (e && e.target) ? [e.target.result] : [null];
hasCallback && win(result);
};
op.onerror = function () { };
op.start();
}
});
},
injectScriptFile: function (win, fail, args) {
setImmediate(function () {
var filePath = args[0],
hasCallback = args[1];
if (!!filePath) {
filePath = urlutil.makeAbsolute(filePath);
}
if (isWebViewAvailable && browserWrap && popup) {
var uri = new Windows.Foundation.Uri(filePath);
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 result = [e.target.result];
hasCallback && win(result);
};
op.onerror = function () { };
op.start();
});
});
}
});
},
injectStyleCode: function (win, fail, args) {
setImmediate(function () {
var code = args[0],
hasCallback = args[1];
if (isWebViewAvailable && browserWrap && popup) {
injectCSS(popup, code, hasCallback && win);
}
});
},
injectStyleFile: function (win, fail, args) {
setImmediate(function () {
var filePath = args[0],
hasCallback = args[1];
filePath = filePath && urlutil.makeAbsolute(filePath);
if (isWebViewAvailable && browserWrap && popup) {
var uri = new Windows.Foundation.Uri(filePath);
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(function (file) {
return Windows.Storage.FileIO.readTextAsync(file);
}).done(function (code) {
injectCSS(popup, code, hasCallback && win);
}, function () {
// no-op, just catch an error
});
}
});
}
};
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)"
.replace('%s', escapedCode);
var op = webView.invokeScriptAsync("eval", evalWrapper);
op.oncomplete = function() {
callback && callback([]);
};
op.onerror = function () { };
op.start();
}
module.exports = IAB;
require("cordova/exec/proxy").add("InAppBrowser", module.exports);

View File

@@ -1,21 +1,38 @@
using System;
using System.Net;
/*
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.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using System.Runtime.Serialization;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
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
{
@@ -36,12 +53,50 @@ namespace WPCordovaClassLib.Cordova.Commands
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
@@ -59,8 +114,96 @@ namespace WPCordovaClassLib.Cordova.Commands
ShowSystemBrowser(urlLoc);
break;
}
}
public void show(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
if (browser != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
browser.Visibility = Visibility.Visible;
AppBar.IsVisible = true;
});
}
}
public void injectScriptCode(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
bool bCallback = false;
if (bool.TryParse(args[1], out bCallback)) { };
string callbackId = args[2];
if (browser != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var res = browser.InvokeScript("eval", new string[] { args[0] });
if (bCallback)
{
PluginResult result = new PluginResult(PluginResult.Status.OK, res.ToString());
result.KeepCallback = false;
this.DispatchCommandResult(result);
}
});
}
}
public void injectScriptFile(string options)
{
Debug.WriteLine("Error : Windows Phone cordova-plugin-inappbrowser does not currently support executeScript");
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
// throw new NotImplementedException("Windows Phone does not currently support 'executeScript'");
}
public void injectStyleCode(string options)
{
Debug.WriteLine("Error : Windows Phone cordova-plugin-inappbrowser does not currently support insertCSS");
return;
//string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
//bool bCallback = false;
//if (bool.TryParse(args[1], out bCallback)) { };
//string callbackId = args[2];
//if (browser != null)
//{
//Deployment.Current.Dispatcher.BeginInvoke(() =>
//{
// if (bCallback)
// {
// string cssInsertString = "try{(function(doc){var c = '<style>body{background-color:#ffff00;}</style>'; doc.head.innerHTML += c;})(document);}catch(ex){alert('oops : ' + ex.message);}";
// //cssInsertString = cssInsertString.Replace("_VALUE_", args[0]);
// Debug.WriteLine("cssInsertString = " + cssInsertString);
// var res = browser.InvokeScript("eval", new string[] { cssInsertString });
// if (bCallback)
// {
// PluginResult result = new PluginResult(PluginResult.Status.OK, res.ToString());
// result.KeepCallback = false;
// this.DispatchCommandResult(result);
// }
// }
//});
//}
}
public void injectStyleFile(string options)
{
Debug.WriteLine("Error : Windows Phone cordova-plugin-inappbrowser does not currently support insertCSS");
return;
//string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
//throw new NotImplementedException("Windows Phone does not currently support 'insertCSS'");
}
private void ShowCordovaBrowser(string url)
@@ -78,7 +221,7 @@ namespace WPCordovaClassLib.Cordova.Commands
if (cView != null)
{
WebBrowser br = cView.Browser;
br.Navigate(loc);
br.Navigate2(loc);
}
}
@@ -86,24 +229,64 @@ namespace WPCordovaClassLib.Cordova.Commands
});
}
#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);
Uri loc = new Uri(url, UriKind.RelativeOrAbsolute);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (browser != null)
{
//browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
browser.Navigate(loc);
browser.Navigate2(loc);
}
else
{
@@ -126,7 +309,13 @@ namespace WPCordovaClassLib.Cordova.Commands
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.Navigate(loc);
browser.Navigate2(loc);
if (StartHidden)
{
browser.Visibility = Visibility.Collapsed;
}
//browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
grid.Children.Add(browser);
}
@@ -156,6 +345,11 @@ namespace WPCordovaClassLib.Cordova.Commands
bar.Buttons.Add(closeBtn);
page.ApplicationBar = bar;
bar.IsVisible = !StartHidden;
AppBar = bar;
page.BackKeyPress += page_BackKeyPress;
}
}
@@ -163,6 +357,23 @@ namespace WPCordovaClassLib.Cordova.Commands
});
}
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)
{
@@ -195,7 +406,7 @@ namespace WPCordovaClassLib.Cordova.Commands
{
#if WP8
browser.GoBack();
#else
#else
browser.InvokeScript("execScript", "history.back();");
#endif
}
@@ -230,13 +441,15 @@ namespace WPCordovaClassLib.Cordova.Commands
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);
this.DispatchCommandResult(result, NavigationCallbackId);
});
}
}
@@ -251,27 +464,52 @@ namespace WPCordovaClassLib.Cordova.Commands
}
#endif
string message = "{\"type\":\"loadstop\", \"url\":\"" + e.Uri.AbsoluteUri + "\"}";
string message = "{\"type\":\"loadstop\", \"url\":\"" + e.Uri.OriginalString + "\"}";
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
result.KeepCallback = true;
this.DispatchCommandResult(result);
this.DispatchCommandResult(result, NavigationCallbackId);
}
void browser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
{
string message = "{\"type\":\"error\",\"url\":\"" + e.Uri.AbsoluteUri + "\"}";
string message = "{\"type\":\"error\",\"url\":\"" + e.Uri.OriginalString + "\"}";
PluginResult result = new PluginResult(PluginResult.Status.ERROR, message);
result.KeepCallback = true;
this.DispatchCommandResult(result);
this.DispatchCommandResult(result, NavigationCallbackId);
}
void browser_Navigating(object sender, NavigatingEventArgs e)
{
string message = "{\"type\":\"loadstart\",\"url\":\"" + e.Uri.AbsoluteUri + "\"}";
string message = "{\"type\":\"loadstart\",\"url\":\"" + e.Uri.OriginalString + "\"}";
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
result.KeepCallback = true;
this.DispatchCommandResult(result);
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);
}
}
}
}

BIN
test/.DS_Store vendored

Binary file not shown.

70
test/cordova-incl.js vendored
View File

@@ -1,70 +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.
*
*/
var PLAT;
if (/Android/.exec(navigator.userAgent)) {
PLAT = 'android';
} else if (/(iPad)|(iPhone)|(iPod)/.exec(navigator.userAgent)) {
PLAT = 'ios';
} else if (/(BB10)|(PlayBook)|(BlackBerry)/.exec(navigator.userAgent)) {
PLAT = 'blackberry';
}
var scripts = document.getElementsByTagName('script');
var currentPath = scripts[scripts.length - 1].src;
var platformCordovaPath = currentPath.replace("cordova-incl.js", "cordova." + PLAT + ".js");
var normalCordovaPath = currentPath.replace("cordova-incl.js", "cordova.js");
var cordovaPath = normalCordovaPath;
if (PLAT) {
// XHR to local file is an error on some platforms, windowsphone for one
try {
var xhr = new XMLHttpRequest();
xhr.open("GET", platformCordovaPath, false);
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE && this.responseText.length > 0) {
if(parseInt(this.status) >= 400){
cordovaPath = normalCordovaPath;
}else{
cordovaPath = platformCordovaPath;
}
}
};
xhr.send(null);
}
catch(e){
cordovaPath = normalCordovaPath;
} // access denied!
}
if (!window._doNotWriteCordovaScript) {
document.write('<script type="text/javascript" charset="utf-8" src="' + cordovaPath + '"></script>');
}
function backHome() {
if (window.device && device.platform && device.platform.toLowerCase() == 'android') {
navigator.app.backHistory();
}
else {
window.history.go(-1);
}
}

View File

@@ -1,258 +0,0 @@
<!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta name="viewport" content="width=device-width,height=device-height,user-scalable=no,maximum-scale=1.0,initial-scale=1.0" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8"> <!-- ISO-8859-1 -->
<title>Cordova Mobile Spec</title>
<link rel="stylesheet" href="../master.css" type="text/css" media="screen" title="no title" charset="utf-8">
<script type="text/javascript" charset="utf-8" src="../cordova-incl.js"></script>
<script type="text/javascript" charset="utf-8">
var deviceReady = false;
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {
deviceReady = true;
console.log("Device="+device.platform+" "+device.version);
}, false);
function updateUserAgent() {
document.getElementById("user-agent").textContent = navigator.userAgent;
}
updateUserAgent();
window.setInterval(updateUserAgent, 1500);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: Apache Cordova did not initialize. Demo will not run correctly.");
}
},1000);
}
function doOpen(url, target, params, numExpectedRedirects) {
numExpectedRedirects = numExpectedRedirects || 0;
var iab = window.open(url, target, params);
if (!iab) {
alert('window.open returned ' + iab);
return;
}
var counts;
var lastLoadStartURL;
var wasReset = false;
function reset() {
counts = {
'loaderror': 0,
'loadstart': 0,
'loadstop': 0,
'exit': 0
};
lastLoadStartURL = '';
}
reset();
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.');
}
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 (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'] + ')');
}
} else if (numExpectedRedirects > 0 && counts['loadstart'] < (numExpectedRedirects+1)) {
alert('Unexpected: should have got at least ' + (numExpectedRedirects+1) + ' loadstart events, but got ' + counts['loadstart']);
}
wasReset = true;
numExpectedRedirects = 0;
reset();
}
// Verify that loadend / loaderror was called.
if (e.type == 'exit') {
var numStopEvents = counts['loadstop'] + counts['loaderror'];
if (numStopEvents === 0 && !wasReset) {
alert('Unexpected: browser closed without a loadstop or loaderror.')
} else if (numStopEvents > 1) {
alert('Unexpected: got multiple loadstop/loaderror events.');
}
}
}
iab.addEventListener('loaderror', logEvent, false);
iab.addEventListener('loadstart', logEvent, false);
iab.addEventListener('loadstop', logEvent, false);
iab.addEventListener('exit', logEvent, false);
return iab;
}
function openWithStyle(url, cssUrl, useCallback) {
var iab = doOpen(url, '_blank', 'location=yes');
var callback = function(results) {
if (results && results.length === 0) {
alert('Results verified');
} else {
console.log(results);
alert('Got: ' + typeof(results) + '\n' + JSON.stringify(results));
}
};
if (cssUrl) {
iab.addEventListener('loadstop', function(event) {
iab.insertCSS({file: cssUrl}, useCallback && callback);
});
} else {
iab.addEventListener('loadstop', function(event) {
iab.insertCSS({code:'#style-update-literal { \ndisplay: block !important; \n}'},
useCallback && callback);
});
}
}
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');
} else {
console.log(results);
alert('Got: ' + typeof(results) + '\n' + JSON.stringify(results));
}
});
});
} else {
iab.addEventListener('loadstop', function(event) {
var code = '(function(){\n' +
' var header = document.getElementById("header");\n' +
' header.innerHTML = "Script literal successfully injected";\n' +
' return "abc";\n' +
'})()';
iab.executeScript({code:code}, useCallback && function(results) {
if (results && results.length === 1 && results[0] === 'abc') {
alert('Results verified');
} else {
console.log(results);
alert('Got: ' + typeof(results) + '\n' + JSON.stringify(results));
}
});
});
}
}
var hiddenwnd=null;
var loadlistener = function(event) { alert('background window loaded ' ); };
function openHidden(url, startHidden) {
var shopt =(startHidden) ? 'hidden=yes' : '';
hiddenwnd = window.open(url,'random_string',shopt);
if (!hiddenwnd) {
alert('window.open returned ' + hiddenwnd);
return;
}
if(startHidden) hiddenwnd.addEventListener('loadstop', loadlistener);
}
function showHidden() {
if(!!hiddenwnd ) {
hiddenwnd.show();
}
}
function closeHidden() {
if(!!hiddenwnd ) {
hiddenwnd.removeEventListener('loadstop',loadlistener);
hiddenwnd.close();
hiddenwnd=null;
}
}
</script>
</head>
<body onload="init();" id="stage" class="theme">
<h1>InAppBrowser</h1>
<div id="info">
Make sure http://www.google.com is white listed. </br>
Make sure http://www.apple.com is not in the white list.</br> In iOS, starred <span style="vertical-align:super">*</span> tests will leave the app with no way to return. </br>
<h4>User-Agent: <span id="user-agent"> </span></h4>
</div>
<div onclick="backHome();">Back</div>
<h1>Local URL</h1>
<div class="btn large" onclick="doOpen('local.html');">Default: CordovaWebView</div>
<div class="btn large" onclick="doOpen('local.html', '_self');">Target=Self: CordovaWebView</div>
<div class="btn large" onclick="doOpen('local.html', '_system');">Target=System: Error</div>
<div class="btn large" onclick="doOpen('local.html', '_blank');">Target=Blank: InAppBrowser</div>
<div class="btn large" onclick="doOpen('local.html', 'random_string');">Target=Random: InAppBrowser</div>
<div class="btn large" onclick="doOpen('local.html', 'random_string', 'location=no');">Target=Random, no location bar: InAppBrowser</div>
<h1>White Listed URL</h1>
<div class="btn large" onclick="doOpen('http://www.google.com');">Default: CordovaWebView<span style="vertical-align:super">*</span></div>
<div class="btn large" onclick="doOpen('http://www.google.com', '_self');">Target=Self: CordovaWebView<span style="vertical-align:super">*</span></div>
<div class="btn large" onclick="doOpen('http://www.google.com', '_system');">Target=System: System Browser</div>
<div class="btn large" onclick="doOpen('http://www.google.com', '_blank');">Target=Blank: InAppBrowser</div>
<div class="btn large" onclick="doOpen('http://www.google.com', 'random_string');">Target=Random: InAppBrowser</div>
<div class="btn large" onclick="doOpen('http://www.google.com', 'random_string', 'location=no');">Target=Random, no location bar: InAppBrowser</div>
<h1>Non White Listed URL</h1>
<div class="btn large" onclick="doOpen('http://www.apple.com');">Default: InAppBrowser</div>
<div class="btn large" onclick="doOpen('http://www.apple.com', '_self');">Target=Self: InAppBrowser</div>
<div class="btn large" onclick="doOpen('http://www.apple.com', '_system');">Target=System: System</div>
<div class="btn large" onclick="doOpen('http://www.apple.com', '_blank');">Target=Blank: InAppBrowser</div>
<div class="btn large" onclick="doOpen('http://www.apple.com', 'random_string');">Target=Random: InAppBrowser</div>
<div class="btn large" onclick="doOpen('http://www.apple.com', 'random_string', 'location=no');">Target=Random, no location bar: InAppBrowser</div>
<h1>Page with redirect</h1>
<div class="btn large" onclick="doOpen('http://google.com', 'random_string', '', 1);">http://google.com (should 301)</div>
<div class="btn large" onclick="doOpen('http://goo.gl/pUFqg', 'random_string', '', 2);">http://www.zhihu.com/answer/16714076 (should 302)</div>
<h1>PDF URL</h1>
<div class="btn large" onclick="doOpen('http://www.stluciadance.com/prospectus_file/sample.pdf');">Remote URL</div>
<div class="btn large" onclick="doOpen('local.pdf', '_blank');">Local URL</div>
<h1>INVALID URL</h1>
<div class="btn large" onclick="doOpen('x-ttp://www.invalid.com/', '_blank');">Invalid Scheme</div>
<div class="btn large" onclick="doOpen('http://www.inv;alid.com/', '_blank');">Invalid Host</div>
<div class="btn large" onclick="doOpen('nonexistent.html', '_blank');">Missing File</div>
<h1>CSS / JS Injection</h1>
<div class="btn large" onclick="doOpen('inject.html', '_blank');">Original Document</div>
<div class="btn large" onclick="openWithStyle('inject.html','inject.css');">CSS File Injection</div>
<div class="btn large" onclick="openWithStyle('inject.html','inject.css', true);">CSS File Injection (CB)</div>
<div class="btn large" onclick="openWithStyle('inject.html');">CSS Literal Injection</div>
<div class="btn large" onclick="openWithStyle('inject.html', null, true);">CSS Literal Injection (CB)</div>
<div class="btn large" onclick="openWithScript('inject.html', 'inject.js');">Script File Injection</div>
<div class="btn large" onclick="openWithScript('inject.html', 'inject.js', true);">Script File Injection (CB)</div>
<div class="btn large" onclick="openWithScript('inject.html');">Script Literal Injection</div>
<div class="btn large" onclick="openWithScript('inject.html', null, true);">Script Literal Injection (CB)</div>
<h1>Open Hidden </h1>
<div class="btn large" onclick="openHidden('http://google.com',true);">google.com hidden</div>
<div class="btn large" onclick="showHidden();">show hidden</div>
<div class="btn large" onclick="closeHidden();">close hidden</div>
<div class="btn large" onclick="openHidden('http://google.com',false);">google.com not hidden</div>
<h2> </h2><div class="backBtn" onclick="backHome();">Back</div>
</body>
</html>

View File

@@ -1,65 +0,0 @@
<!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta name="viewport" content="width=device-width,height=device-height,user-scalable=no,initial-scale=1.0" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Cordova Mobile Spec</title>
<link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova-incl.js"></script>
<script type="text/javascript" charset="utf-8" src="main.js"></script>
</head>
<body onload="init();" id="stage" class="theme">
<h1>Apache Cordova Tests</h1>
<div id="info">
<h4>Platform: <span id="platform"> </span></h4>
<h4>Version: <span id="version"> </span></h4>
<h4>UUID: <span id="uuid"> </span></h4>
<h4>Name: <span id="name"> </span></h4>
<h4>Model: <span id="model"> </span></h4>
<h4>Width: <span id="width"> </span>, Height: <span id="height">
</span>, Color Depth: <span id="colorDepth"></span></h4>
<h4>User-Agent: <span id="user-agent"> </span></h4>
</div>
<a href="autotest/index.html" class="btn large">Automatic Test</a>
<a href="accelerometer/index.html" class="btn large">Accelerometer</a>
<a href="audio/index.html" class="btn large">Audio Play/Record</a>
<a href="battery/index.html" class="btn large">Battery</a>
<a href="camera/index.html" class="btn large">Camera</a>
<a href="compass/index.html" class="btn large">Compass</a>
<a href="contacts/index.html" class="btn large">Contacts</a>
<a href="events/index.html" class="btn large">Events</a>
<a href="location/index.html" class="btn large">Location</a>
<a href="lazyloadjs/index.html" class="btn large">Lazy Loading of cordova-incl.js</a>
<a href="misc/index.html" class="btn large">Misc Content</a>
<a href="network/index.html" class="btn large">Network</a>
<a href="notification/index.html" class="btn large">Notification</a>
<a href="splashscreen/index.html" class="btn large">Splashscreen</a>
<a href="sql/index.html" class="btn large">Web SQL</a>
<a href="storage/index.html" class="btn large">Local Storage</a>
<a href="benchmarks/index.html" class="btn large">Benchmarks</a>
<a href="inappbrowser/index.html" class="btn large">In App Browser</a>
</body>
</html>

View File

@@ -1,163 +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.
*
*/
var deviceInfo = function() {
document.getElementById("platform").innerHTML = device.platform;
document.getElementById("version").innerHTML = device.version;
document.getElementById("uuid").innerHTML = device.uuid;
document.getElementById("name").innerHTML = device.name;
document.getElementById("model").innerHTML = device.model;
document.getElementById("width").innerHTML = screen.width;
document.getElementById("height").innerHTML = screen.height;
document.getElementById("colorDepth").innerHTML = screen.colorDepth;
};
var getLocation = function() {
var suc = function(p) {
alert(p.coords.latitude + " " + p.coords.longitude);
};
var locFail = function() {
};
navigator.geolocation.getCurrentPosition(suc, locFail);
};
var beep = function() {
navigator.notification.beep(2);
};
var vibrate = function() {
navigator.notification.vibrate(0);
};
function roundNumber(num) {
var dec = 3;
var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
return result;
}
var accelerationWatch = null;
function updateAcceleration(a) {
document.getElementById('x').innerHTML = roundNumber(a.x);
document.getElementById('y').innerHTML = roundNumber(a.y);
document.getElementById('z').innerHTML = roundNumber(a.z);
}
var toggleAccel = function() {
if (accelerationWatch !== null) {
navigator.accelerometer.clearWatch(accelerationWatch);
updateAcceleration({
x : "",
y : "",
z : ""
});
accelerationWatch = null;
} else {
var options = {};
options.frequency = 1000;
accelerationWatch = navigator.accelerometer.watchAcceleration(
updateAcceleration, function(ex) {
alert("accel fail (" + ex.name + ": " + ex.message + ")");
}, options);
}
};
var preventBehavior = function(e) {
e.preventDefault();
};
function dump_pic(data) {
var viewport = document.getElementById('viewport');
console.log(data);
viewport.style.display = "";
viewport.style.position = "absolute";
viewport.style.top = "10px";
viewport.style.left = "10px";
document.getElementById("test_img").src = "data:image/jpeg;base64," + data;
}
function fail(msg) {
alert(msg);
}
function show_pic() {
navigator.camera.getPicture(dump_pic, fail, {
quality : 50
});
}
function close() {
var viewport = document.getElementById('viewport');
viewport.style.position = "relative";
viewport.style.display = "none";
}
// This is just to do this.
function readFile() {
navigator.file.read('/sdcard/cordova.txt', fail, fail);
}
function writeFile() {
navigator.file.write('foo.txt', "This is a test of writing to a file",
fail, fail);
}
function contacts_success(contacts) {
alert(contacts.length
+ ' contacts returned.'
+ (contacts[2] && contacts[2].name ? (' Third contact is ' + contacts[2].name.formatted)
: ''));
}
function get_contacts() {
var obj = new ContactFindOptions();
obj.filter = "";
obj.multiple = true;
obj.limit = 5;
navigator.service.contacts.find(
[ "displayName", "name" ], contacts_success,
fail, obj);
}
var networkReachableCallback = function(reachability) {
// There is no consistency on the format of reachability
var networkState = reachability.code || reachability;
var currentState = {};
currentState[NetworkStatus.NOT_REACHABLE] = 'No network connection';
currentState[NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK] = 'Carrier data connection';
currentState[NetworkStatus.REACHABLE_VIA_WIFI_NETWORK] = 'WiFi connection';
confirm("Connection type:\n" + currentState[networkState]);
};
function check_network() {
navigator.network.isReachable("www.mobiledevelopersolutions.com",
networkReachableCallback, {});
}
function init() {
// the next line makes it impossible to see Contacts on the HTC Evo since it
// doesn't have a scroll button
// document.addEventListener("touchmove", preventBehavior, false);
document.addEventListener("deviceready", deviceInfo, true);
document.getElementById("user-agent").textContent = navigator.userAgent;
}

View File

@@ -1,164 +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.
*
*/
body {
background:#222 none repeat scroll 0 0;
color:#666;
font-family:Helvetica;
font-size:72%;
line-height:1.5em;
margin:0;
border-top:1px solid #393939;
}
#info{
background:#ffa;
border: 1px solid #ffd324;
-webkit-border-radius: 5px;
border-radius: 5px;
clear:both;
margin:15px 6px 0;
min-width:295px;
max-width:97%;
padding:4px 0px 2px 10px;
word-wrap:break-word;
margin-bottom:10px;
display:inline-block;
min-height: 160px;
max-height: 300px;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
#info > h4{
font-size:.95em;
margin:5px 0;
}
#stage.theme{
padding-top:3px;
}
/* Definition List */
#stage.theme > dl{
padding-top:10px;
clear:both;
margin:0;
list-style-type:none;
padding-left:10px;
overflow:auto;
}
#stage.theme > dl > dt{
font-weight:bold;
float:left;
margin-left:5px;
}
#stage.theme > dl > dd{
width:45px;
float:left;
color:#a87;
font-weight:bold;
}
/* Content Styling */
#stage.theme > h1, #stage.theme > h2, #stage.theme > p{
margin:1em 0 .5em 13px;
}
#stage.theme > h1{
color:#eee;
font-size:1.6em;
text-align:center;
margin:0;
margin-top:15px;
padding:0;
}
#stage.theme > h2{
clear:both;
margin:0;
padding:3px;
font-size:1em;
text-align:center;
}
/* Stage Buttons */
#stage.theme .btn{
border: 1px solid #555;
-webkit-border-radius: 5px;
border-radius: 5px;
text-align:center;
display:inline-block;
background:#444;
width:150px;
color:#9ab;
font-size:1.1em;
text-decoration:none;
padding:1.2em 0;
margin:3px 0px 3px 5px;
}
#stage.theme .large{
width:308px;
padding:1.2em 0;
}
#stage.theme .wide{
width:100%;
padding:1.2em 0;
}
#stage.theme .backBtn{
border: 1px solid #555;
-webkit-border-radius: 5px;
border-radius: 5px;
text-align:center;
display:block;
float:right;
background:#666;
width:75px;
color:#9ab;
font-size:1.1em;
text-decoration:none;
padding:1.2em 0;
margin:3px 5px 3px 5px;
}
#stage.theme .input{
border: 1px solid #555;
-webkit-border-radius: 5px;
border-radius: 5px;
text-align:center;
display:block;
float:light;
background:#888;
color:#9cd;
font-size:1.1em;
text-decoration:none;
padding:1.2em 0;
margin:3px 0px 3px 5px;
}
#stage.theme .numeric{
width:100%;
}

33
tests/plugin.xml Normal file
View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="cordova-plugin-inappbrowser-tests"
version="1.2.1">
<name>Cordova InAppBrowser Plugin Tests</name>
<license>Apache 2.0</license>
<dependency id="cordova-plugin-dialogs" />
<js-module src="tests.js" name="tests">
</js-module>
<asset src="resources" target="cdvtests/iab-resources" />
</plugin>

View File

@@ -26,12 +26,13 @@
<meta name="viewport" content="width=device-width,height=device-height,user-scalable=no,maximum-scale=1.0,initial-scale=1.0" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8"> <!-- ISO-8859-1 -->
<title>Cordova Mobile Spec</title>
<link rel="stylesheet" href="../master.css" type="text/css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="../../master.css" type="text/css" media="screen" title="no title" charset="utf-8">
</head>
<body id="stage" class="theme">
<h1 id="header">InAppBrowser - Script / Style Injection Test</h1>
<h2 id="style-update-file" style="display:none">Style updated from file</h2>
<h2 id="style-update-literal" style="display:none">Style updated from literal</h2>
<div>User-Agent: <cite id="u-a"></cite></div>
</body>
<script>
function updateUserAgent() {

View File

@@ -0,0 +1,67 @@
<!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta name="viewport" content="width=device-width,height=device-height,user-scalable=no,maximum-scale=1.0,initial-scale=1.0" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8"> <!-- ISO-8859-1 -->
<title>IAB test page</title>
<script type="text/javascript" charset="utf-8" src="../../cordova-incl.js"></script>
<script type="text/javascript" charset="utf-8">
function onDeviceReady() {
document.getElementById("hint").textContent = "Running CordovaWebView, deviceVersion=" + device.version + ", no toolbar should be present, Back link should work, logcat should NOT have failed 'gap:' calls.";
}
document.addEventListener("deviceready", onDeviceReady, false);
</script>
<style>
body {background-color: #ffffff;}
</style>
</head>
<body id="stage" class="theme">
<h1>Local URL</h1>
<div id="info">
You have successfully loaded a local URL:
<script>document.write(location.href)</script>
</div>
<hr />
<div>User-Agent = <span id="u-a"></span></div>
<hr />
<div id="hint">Likely running inAppBrowser: Device version from Cordova=not found, Back link should not work, toolbar may be present, logcat should show failed 'gap:' calls.</div>
<hr />
<div><a href="http://www.google.com">Visit Google</a> (whitelisted)</div>
<div><a href="http://www.yahoo.com">Visit Yahoo</a> (not whitelisted)</div>
<div><a href="http://www.stluciadance.com/prospectus_file/sample.pdf">Check out my remote PDF</a></div>
<div><a href="local.pdf">Check out my local PDF</a></div>
<p /><a href="javascript:;" onclick="history.back();">Back</a>
<p />
<a name="anchor2"></a>
<div style="height: 1000px;border:1px solid red;">tall div with border</div>
</body>
<script>
function updateUserAgent() {
document.getElementById("u-a").textContent = navigator.userAgent;
}
updateUserAgent();
window.setInterval(updateUserAgent, 1500);
</script>
</html>

View File

@@ -26,26 +26,17 @@
<meta name="viewport" content="width=device-width,height=device-height,user-scalable=no,maximum-scale=1.0,initial-scale=1.0" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8"> <!-- ISO-8859-1 -->
<title>Cordova Mobile Spec</title>
<link rel="stylesheet" href="../master.css" type="text/css" media="screen" title="no title" charset="utf-8">
<script type="text/javascript" charset="utf-8" src="../cordova-incl.js"></script>
</head>
<body id="stage" class="theme">
<h1>InAppBrowser - Local URL</h1>
<div id="info">
You have successfully loaded a local URL
</div>
<div>User-Agent = <span id="u-a"></span></div>
<div><a href="http://www.google.com">Visit Google</a></div>
<div><a href="http://www.yahoo.com">Visit Yahoo</a></div>
<div><a href="http://www.stluciadance.com/prospectus_file/sample.pdf">Check out my remote PDF</a></div>
<div><a href="local.pdf">Check out my local PDF</a></div>
<h2> </h2><div class="backBtn" onclick="backHome();">Back</div>
<body>
<video width=100% height=100% id="player">
<source src="http://m.comptoir-info.com/app/beta/sample.mp4">
<meta property="og:video:secure_url" content="http://m.comptoir-info.com/app/beta/sample.mp4">
<meta property="og:video:type" content="video/mp4">
</video>
<div>
<button onclick="document.getElementById('player').play()"> play </button>
<button onclick="document.getElementById('player').pause()"> pause </button>
</div>
</body>
<script>
function updateUserAgent() {
document.getElementById("u-a").textContent = navigator.userAgent;
}
updateUserAgent();
window.setInterval(updateUserAgent, 1500);
</script>
</html>

623
tests/tests.js Normal file
View File

@@ -0,0 +1,623 @@
/*
*
* 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.
*
*/
var cordova = require('cordova');
var isWindows = cordova.platformId == 'windows';
window.alert = window.alert || navigator.notification.alert;
exports.defineAutoTests = function () {
describe('cordova.InAppBrowser', function () {
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));
});
});
describe('open method', function () {
var iabInstance;
var originalTimeout;
var url = 'http://apache.org/';
var badUrl = 'http://bad-uri/';
beforeEach(function () {
// increase timeout to ensure test url could be loaded within test time
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000;
iabInstance = null;
});
afterEach(function (done) {
// restore original timeout
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
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);
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));
}
it("inappbrowser.spec.3 should retun InAppBrowser instance with required methods", function () {
iabInstance = cordova.InAppBrowser.open(url, '_blank');
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.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');
});
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.5 should support exit event", function (done) {
iabInstance = cordova.InAppBrowser.open(url, '_blank');
iabInstance.addEventListener('exit', function (evt) {
verifyEvent(evt, 'exit');
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();
});
});
});
};
exports.defineManualTests = function (contentEl, createActionButton) {
function doOpen(url, target, params, numExpectedRedirects, useWindowOpen) {
numExpectedRedirects = numExpectedRedirects || 0;
useWindowOpen = useWindowOpen || false;
console.log("Opening " + url);
var counts;
var lastLoadStartURL;
var wasReset = false;
function reset() {
counts = {
'loaderror': 0,
'loadstart': 0,
'loadstop': 0,
'exit': 0
};
lastLoadStartURL = '';
}
reset();
var iab;
var callbacks = {
loaderror: logEvent,
loadstart: logEvent,
loadstop: logEvent,
exit: logEvent
};
if (useWindowOpen) {
console.log('Use window.open() for url');
iab = window.open(url, target, params, callbacks);
}
else {
iab = cordova.InAppBrowser.open(url, target, params, callbacks);
}
if (!iab) {
alert('open returned ' + iab);
return;
}
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.');
}
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 (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'] + ')');
}
} else if (numExpectedRedirects > 0 && counts['loadstart'] < (numExpectedRedirects + 1)) {
alert('Unexpected: should have got at least ' + (numExpectedRedirects + 1) + ' loadstart events, but got ' + counts['loadstart']);
}
wasReset = true;
numExpectedRedirects = 0;
reset();
}
// Verify that loadend / loaderror was called.
if (e.type == 'exit') {
var numStopEvents = counts['loadstop'] + counts['loaderror'];
if (numStopEvents === 0 && !wasReset) {
alert('Unexpected: browser closed without a loadstop or loaderror.');
} else if (numStopEvents > 1) {
alert('Unexpected: got multiple loadstop/loaderror events.');
}
}
}
return iab;
}
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 {
if (wasClobbered) {
window.open = originalFunc;
}
else {
console.log('just delete, to restore open from prototype');
delete window.open;
}
}
}
function openWithStyle(url, cssUrl, useCallback) {
var iab = doOpen(url, '_blank', 'location=yes');
var callback = function (results) {
if (results && results.length === 0) {
alert('Results verified');
} else {
console.log(results);
alert('Got: ' + typeof (results) + '\n' + JSON.stringify(results));
}
};
if (cssUrl) {
iab.addEventListener('loadstop', function (event) {
iab.insertCSS({ file: cssUrl }, useCallback && callback);
});
} else {
iab.addEventListener('loadstop', function (event) {
iab.insertCSS({ code: '#style-update-literal { \ndisplay: block !important; \n}' },
useCallback && callback);
});
}
}
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');
} else {
console.log(results);
alert('Got: ' + typeof (results) + '\n' + JSON.stringify(results));
}
});
});
} else {
iab.addEventListener('loadstop', function (event) {
var code = '(function(){\n' +
' var header = document.getElementById("header");\n' +
' header.innerHTML = "Script literal successfully injected";\n' +
' return "abc";\n' +
'})()';
iab.executeScript({ code: code }, useCallback && function (results) {
if (results && results.length === 1 && results[0] === 'abc') {
alert('Results verified');
} else {
console.log(results);
alert('Got: ' + typeof (results) + '\n' + JSON.stringify(results));
}
});
});
}
}
var hiddenwnd = null;
var loadlistener = function (event) { alert('background window loaded '); };
function openHidden(url, startHidden) {
var shopt = (startHidden) ? 'hidden=yes' : '';
hiddenwnd = cordova.InAppBrowser.open(url, 'random_string', shopt);
if (!hiddenwnd) {
alert('cordova.InAppBrowser.open returned ' + hiddenwnd);
return;
}
if (startHidden) hiddenwnd.addEventListener('loadstop', loadlistener);
}
function showHidden() {
if (!!hiddenwnd) {
hiddenwnd.show();
}
}
function closeHidden() {
if (!!hiddenwnd) {
hiddenwnd.removeEventListener('loadstop', loadlistener);
hiddenwnd.close();
hiddenwnd = null;
}
}
var info_div = '<h1>InAppBrowser</h1>' +
'<div id="info">' +
'Make sure http://cordova.apache.org and http://google.co.uk and https://www.google.co.uk are white listed. </br>' +
'Make sure http://www.apple.com is not in the white list.</br>' +
'In iOS, starred <span style="vertical-align:super">*</span> tests will put the app in a state with no way to return. </br>' +
'<h4>User-Agent: <span id="user-agent"> </span></hr>' +
'</div>';
var local_tests = '<h1>Local URL</h1>' +
'<div id="openLocal"></div>' +
'Expected result: opens successfully in CordovaWebView.' +
'<p/> <div id="openLocalHook"></div>' +
'Expected result: opens successfully in CordovaWebView (using hook of window.open()).' +
'<p/> <div id="openLocalSelf"></div>' +
'Expected result: opens successfully in CordovaWebView.' +
'<p/> <div id="openLocalSystem"></div>' +
'Expected result: fails to open' +
'<p/> <div id="openLocalBlank"></div>' +
'Expected result: opens successfully in InAppBrowser with locationBar at top.' +
'<p/> <div id="openLocalRandomNoLocation"></div>' +
'Expected result: opens successfully in InAppBrowser without locationBar.' +
'<p/> <div id="openLocalRandomToolBarBottom"></div>' +
'Expected result: opens successfully in InAppBrowser with locationBar. On iOS the toolbar is at the bottom.' +
'<p/> <div id="openLocalRandomToolBarTop"></div>' +
'Expected result: opens successfully in InAppBrowser with locationBar. On iOS the toolbar is at the top.' +
'<p/><div id="openLocalRandomToolBarTopNoLocation"></div>' +
'Expected result: open successfully in InAppBrowser with no locationBar. On iOS the toolbar is at the top.';
var white_listed_tests = '<h1>White Listed URL</h1>' +
'<div id="openWhiteListed"></div>' +
'Expected result: open successfully in CordovaWebView to cordova.apache.org' +
'<p/> <div id="openWhiteListedHook"></div>' +
'Expected result: open successfully in CordovaWebView to cordova.apache.org (using hook of window.open())' +
'<p/> <div id="openWhiteListedSelf"></div>' +
'Expected result: open successfully in CordovaWebView to cordova.apache.org' +
'<p/> <div id="openWhiteListedSystem"></div>' +
'Expected result: open successfully in system browser to cordova.apache.org' +
'<p/> <div id="openWhiteListedBlank"></div>' +
'Expected result: open successfully in InAppBrowser to cordova.apache.org' +
'<p/> <div id="openWhiteListedRandom"></div>' +
'Expected result: open successfully in InAppBrowser to cordova.apache.org' +
'<p/> <div id="openWhiteListedRandomNoLocation"></div>' +
'Expected result: open successfully in InAppBrowser to cordova.apache.org with no location bar.';
var non_white_listed_tests = '<h1>Non White Listed URL</h1>' +
'<div id="openNonWhiteListed"></div>' +
'Expected result: open successfully in InAppBrowser to apple.com.' +
'<p/> <div id="openNonWhiteListedHook"></div>' +
'Expected result: open successfully in InAppBrowser to apple.com (using hook of window.open()).' +
'<p/> <div id="openNonWhiteListedSelf"></div>' +
'Expected result: open successfully in InAppBrowser to apple.com (_self enforces whitelist).' +
'<p/> <div id="openNonWhiteListedSystem"></div>' +
'Expected result: open successfully in system browser to apple.com.' +
'<p/> <div id="openNonWhiteListedBlank"></div>' +
'Expected result: open successfully in InAppBrowser to apple.com.' +
'<p/> <div id="openNonWhiteListedRandom"></div>' +
'Expected result: open successfully in InAppBrowser to apple.com.' +
'<p/> <div id="openNonWhiteListedRandomNoLocation"></div>' +
'Expected result: open successfully in InAppBrowser to apple.com without locationBar.';
var page_with_redirects_tests = '<h1>Page with redirect</h1>' +
'<div id="openRedirect301"></div>' +
'Expected result: should 301 and open successfully in InAppBrowser to https://www.google.co.uk.' +
'<p/> <div id="openRedirect302"></div>' +
'Expected result: should 302 and open successfully in InAppBrowser to www.zhihu.com/answer/16714076.';
var pdf_url_tests = '<h1>PDF URL</h1>' +
'<div id="openPDF"></div>' +
'Expected result: InAppBrowser opens. PDF should render on iOS.' +
'<p/> <div id="openPDFBlank"></div>' +
'Expected result: InAppBrowser opens. PDF should render on iOS.';
var invalid_url_tests = '<h1>Invalid URL</h1>' +
'<div id="openInvalidScheme"></div>' +
'Expected result: fail to load in InAppBrowser.' +
'<p/> <div id="openInvalidHost"></div>' +
'Expected result: fail to load in InAppBrowser.' +
'<p/> <div id="openInvalidMissing"></div>' +
'Expected result: fail to load in InAppBrowser (404).';
var css_js_injection_tests = '<h1>CSS / JS Injection</h1>' +
'<div id="openOriginalDocument"></div>' +
'Expected result: open successfully in InAppBrowser without text "Style updated from..."' +
'<p/> <div id="openCSSInjection"></div>' +
'Expected result: open successfully in InAppBrowser with "Style updated from file".' +
'<p/> <div id="openCSSInjectionCallback"></div>' +
'Expected result: open successfully in InAppBrowser with "Style updated from file", and alert dialog with text "Results verified".' +
'<p/> <div id="openCSSLiteralInjection"></div>' +
'Expected result: open successfully in InAppBrowser with "Style updated from literal".' +
'<p/> <div id="openCSSLiteralInjectionCallback"></div>' +
'Expected result: open successfully in InAppBrowser with "Style updated from literal", and alert dialog with text "Results verified".' +
'<p/> <div id="openScriptInjection"></div>' +
'Expected result: open successfully in InAppBrowser with text "Script file successfully injected".' +
'<p/> <div id="openScriptInjectionCallback"></div>' +
'Expected result: open successfully in InAppBrowser with text "Script file successfully injected" and alert dialog with the text "Results verified".' +
'<p/> <div id="openScriptLiteralInjection"></div>' +
'Expected result: open successfully in InAppBrowser with the text "Script literal successfully injected" .' +
'<p/> <div id="openScriptLiteralInjectionCallback"></div>' +
'Expected result: open successfully in InAppBrowser with the text "Script literal successfully injected" and alert dialog with the text "Results verified".';
var open_hidden_tests = '<h1>Open Hidden </h1>' +
'<div id="openHidden"></div>' +
'Expected result: no additional browser window. Alert appears with the text "background window loaded".' +
'<p/> <div id="showHidden"></div>' +
'Expected result: after first clicking on previous test "create hidden", open successfully in InAppBrowser to https://www.google.co.uk.' +
'<p/> <div id="closeHidden"></div>' +
'Expected result: no output. But click on "show hidden" again and nothing should be shown.' +
'<p/> <div id="openHiddenShow"></div>' +
'Expected result: open successfully in InAppBrowser to https://www.google.co.uk';
var clearing_cache_tests = '<h1>Clearing Cache</h1>' +
'<div id="openClearCache"></div>' +
'Expected result: ?' +
'<p/> <div id="openClearSessionCache"></div>' +
'Expected result: ?';
var video_tag_tests = '<h1>Video tag</h1>' +
'<div id="openRemoteVideo"></div>' +
'Expected result: open successfully in InAppBrowser with an embedded video that works after clicking the "play" button.';
var local_with_anchor_tag_tests = '<h1>Local with anchor tag</h1>' +
'<div id="openAnchor1"></div>' +
'Expected result: open successfully in InAppBrowser to the local page, scrolled to the top as normal.' +
'<p/> <div id="openAnchor2"></div>' +
'Expected result: open successfully in InAppBrowser to the local page, scrolled to the beginning of the tall div with border.';
// 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 +
css_js_injection_tests + open_hidden_tests + clearing_cache_tests + video_tag_tests + local_with_anchor_tag_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 +
css_js_injection_tests + open_hidden_tests + clearing_cache_tests + video_tag_tests + local_with_anchor_tag_tests;
}
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';
//Local
createActionButton('target=Default', function () {
doOpen(localhtml);
}, 'openLocal');
createActionButton('target=Default (window.open)', function () {
doHookOpen(localhtml);
}, 'openLocalHook');
createActionButton('target=_self', function () {
doOpen(localhtml, '_self');
}, 'openLocalSelf');
createActionButton('target=_system', function () {
doOpen(localhtml, '_system');
}, 'openLocalSystem');
createActionButton('target=_blank', function () {
doOpen(localhtml, '_blank');
}, 'openLocalBlank');
createActionButton('target=Random, location=no, disallowoverscroll=yes', function () {
doOpen(localhtml, 'random_string', 'location=no, disallowoverscroll=yes');
}, 'openLocalRandomNoLocation');
createActionButton('target=Random, toolbarposition=bottom', function () {
doOpen(localhtml, 'random_string', 'toolbarposition=bottom');
}, 'openLocalRandomToolBarBottom');
createActionButton('target=Random, toolbarposition=top', function () {
doOpen(localhtml, 'random_string', 'toolbarposition=top');
}, 'openLocalRandomToolBarTop');
createActionButton('target=Random, toolbarposition=top, location=no', function () {
doOpen(localhtml, 'random_string', 'toolbarposition=top,location=no');
}, 'openLocalRandomToolBarTopNoLocation');
//White Listed
createActionButton('* target=Default', function () {
doOpen('http://cordova.apache.org');
}, 'openWhiteListed');
createActionButton('* target=Default (window.open)', function () {
doHookOpen('http://cordova.apache.org');
}, 'openWhiteListedHook');
createActionButton('* target=_self', function () {
doOpen('http://cordova.apache.org', '_self');
}, 'openWhiteListedSelf');
createActionButton('target=_system', function () {
doOpen('http://cordova.apache.org', '_system');
}, 'openWhiteListedSystem');
createActionButton('target=_blank', function () {
doOpen('http://cordova.apache.org', '_blank');
}, 'openWhiteListedBlank');
createActionButton('target=Random', function () {
doOpen('http://cordova.apache.org', 'random_string');
}, 'openWhiteListedRandom');
createActionButton('* target=Random, no location bar', function () {
doOpen('http://cordova.apache.org', 'random_string', 'location=no');
}, 'openWhiteListedRandomNoLocation');
//Non White Listed
createActionButton('target=Default', function () {
doOpen('http://www.apple.com');
}, 'openNonWhiteListed');
createActionButton('target=Default (window.open)', function () {
doHookOpen('http://www.apple.com');
}, 'openNonWhiteListedHook');
createActionButton('target=_self', function () {
doOpen('http://www.apple.com', '_self');
}, 'openNonWhiteListedSelf');
createActionButton('target=_system', function () {
doOpen('http://www.apple.com', '_system');
}, 'openNonWhiteListedSystem');
createActionButton('target=_blank', function () {
doOpen('http://www.apple.com', '_blank');
}, 'openNonWhiteListedBlank');
createActionButton('target=Random', function () {
doOpen('http://www.apple.com', 'random_string');
}, 'openNonWhiteListedRandom');
createActionButton('* target=Random, no location bar', function () {
doOpen('http://www.apple.com', 'random_string', 'location=no');
}, 'openNonWhiteListedRandomNoLocation');
//Page with redirect
createActionButton('http://google.co.uk', function () {
doOpen('http://google.co.uk', 'random_string', '', 1);
}, 'openRedirect301');
createActionButton('http://goo.gl/pUFqg', function () {
doOpen('http://goo.gl/pUFqg', 'random_string', '', 2);
}, 'openRedirect302');
//PDF URL
createActionButton('Remote URL', function () {
doOpen('http://www.stluciadance.com/prospectus_file/sample.pdf');
}, 'openPDF');
createActionButton('Local URL', function () {
doOpen(localpdf, '_blank');
}, 'openPDFBlank');
//Invalid URL
createActionButton('Invalid Scheme', function () {
doOpen('x-ttp://www.invalid.com/', '_blank');
}, 'openInvalidScheme');
createActionButton('Invalid Host', function () {
doOpen('http://www.inv;alid.com/', '_blank');
}, 'openInvalidHost');
createActionButton('Missing Local File', function () {
doOpen('nonexistent.html', '_blank');
}, 'openInvalidMissing');
//CSS / JS injection
createActionButton('Original Document', function () {
doOpen(injecthtml, '_blank');
}, 'openOriginalDocument');
createActionButton('CSS File Injection', function () {
openWithStyle(injecthtml, injectcss);
}, 'openCSSInjection');
createActionButton('CSS File Injection (callback)', function () {
openWithStyle(injecthtml, injectcss, true);
}, 'openCSSInjectionCallback');
createActionButton('CSS Literal Injection', function () {
openWithStyle(injecthtml);
}, 'openCSSLiteralInjection');
createActionButton('CSS Literal Injection (callback)', function () {
openWithStyle(injecthtml, null, true);
}, 'openCSSLiteralInjectionCallback');
createActionButton('Script File Injection', function () {
openWithScript(injecthtml, injectjs);
}, 'openScriptInjection');
createActionButton('Script File Injection (callback)', function () {
openWithScript(injecthtml, injectjs, true);
}, 'openScriptInjectionCallback');
createActionButton('Script Literal Injection', function () {
openWithScript(injecthtml);
}, 'openScriptLiteralInjection');
createActionButton('Script Literal Injection (callback)', function () {
openWithScript(injecthtml, null, true);
}, 'openScriptLiteralInjectionCallback');
//Open hidden
createActionButton('Create Hidden', function () {
openHidden('https://www.google.co.uk', true);
}, 'openHidden');
createActionButton('Show Hidden', function () {
showHidden();
}, 'showHidden');
createActionButton('Close Hidden', function () {
closeHidden();
}, 'closeHidden');
createActionButton('google.co.uk Not Hidden', function () {
openHidden('https://www.google.co.uk', false);
}, 'openHiddenShow');
//Clearing cache
createActionButton('Clear Browser Cache', function () {
doOpen('https://www.google.co.uk', '_blank', 'clearcache=yes');
}, 'openClearCache');
createActionButton('Clear Session Cache', function () {
doOpen('https://www.google.co.uk', '_blank', 'clearsessioncache=yes');
}, 'openClearSessionCache');
//Video tag
createActionButton('Remote Video', function () {
doOpen(videohtml, '_blank');
}, 'openRemoteVideo');
//Local With Anchor Tag
createActionButton('Anchor1', function () {
doOpen(localhtml + '#bogusanchor', '_blank');
}, 'openAnchor1');
createActionButton('Anchor2', function () {
doOpen(localhtml + '#anchor2', '_blank');
}, 'openAnchor2');
};

View File

@@ -1,94 +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.
*
*/
var exec = require('cordova/exec');
var channel = require('cordova/channel');
var modulemapper = require('cordova/modulemapper');
function InAppBrowser() {
this.channels = {
'loadstart': channel.create('loadstart'),
'loadstop' : channel.create('loadstop'),
'loaderror' : channel.create('loaderror'),
'exit' : channel.create('exit')
};
}
InAppBrowser.prototype = {
_eventHandler: function (event) {
if (event.type in this.channels) {
this.channels[event.type].fire(event);
}
},
close: function (eventname) {
exec(null, null, "InAppBrowser", "close", []);
},
show: function (eventname) {
exec(null, null, "InAppBrowser", "show", []);
},
addEventListener: function (eventname,f) {
if (eventname in this.channels) {
this.channels[eventname].subscribe(f);
}
},
removeEventListener: function(eventname, f) {
if (eventname in this.channels) {
this.channels[eventname].unsubscribe(f);
}
},
executeScript: function(injectDetails, cb) {
if (injectDetails.code) {
exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
} else if (injectDetails.file) {
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) {
if (injectDetails.code) {
exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
} else if (injectDetails.file) {
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) {
var iab = new InAppBrowser();
var cb = function(eventname) {
iab._eventHandler(eventname);
};
// 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');
return origOpenFunc.apply(window, arguments);
}
exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
return iab;
};

114
www/inappbrowser.css Normal file
View File

@@ -0,0 +1,114 @@
/*
* 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.
*/
.inAppBrowserWrap {
margin: 0;
padding: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: 0 0;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999999;
box-sizing: border-box;
border: 40px solid #bfbfbf;
border: 40px solid rgba(0, 0, 0, 0.25);
}
.inAppBrowserWrapFullscreen {
border: 0;
}
.inappbrowser-app-bar {
height: 70px;
background-color: #404040;
z-index: 9999999;
}
.inappbrowser-app-bar-inner {
padding-top: 10px;
height: 60px;
width: 155px;
margin: 0 auto;
background-color: #404040;
z-index: 9999999;
}
.app-bar-action {
width: auto;
height: 40px;
margin-left: 20px;
font-family: "Segoe UI Symbol";
float: left;
color: white;
font-size: 12px;
text-transform: lowercase;
text-align: center;
cursor: default;
}
.app-bar-action[disabled] {
color: gray;
/*disable click*/
pointer-events: none;
}
.app-bar-action::before {
font-size: 28px;
display: block;
height: 36px;
}
/* Back */
.action-back {
margin-left: 0px;
}
.action-back::before {
content: "\E0BA";
}
.action-back:not([disabled]):hover::before {
content: "\E0B3";
}
/* Forward */
.action-forward::before {
content: "\E0AC";
}
.action-forward:not([disabled]):hover::before {
content: "\E0AF";
}
/* Close */
.action-close::before {
content: "\E0C7";
/* close icon is larger so we re-size it to fit other icons */
font-size: 20px;
line-height: 40px;
}
.action-close:not([disabled]):hover::before {
content: "\E0CA";
}

111
www/inappbrowser.js Normal file
View File

@@ -0,0 +1,111 @@
/*
*
* 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.
*
*/
(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;
}
var exec = require('cordova/exec');
var channel = require('cordova/channel');
var modulemapper = require('cordova/modulemapper');
var urlutil = require('cordova/urlutil');
function InAppBrowser() {
this.channels = {
'loadstart': channel.create('loadstart'),
'loadstop' : channel.create('loadstop'),
'loaderror' : channel.create('loaderror'),
'exit' : channel.create('exit')
};
}
InAppBrowser.prototype = {
_eventHandler: function (event) {
if (event && (event.type in this.channels)) {
this.channels[event.type].fire(event);
}
},
close: function (eventname) {
exec(null, null, "InAppBrowser", "close", []);
},
show: function (eventname) {
exec(null, null, "InAppBrowser", "show", []);
},
addEventListener: function (eventname,f) {
if (eventname in this.channels) {
this.channels[eventname].subscribe(f);
}
},
removeEventListener: function(eventname, f) {
if (eventname in this.channels) {
this.channels[eventname].unsubscribe(f);
}
},
executeScript: function(injectDetails, cb) {
if (injectDetails.code) {
exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
} else if (injectDetails.file) {
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) {
if (injectDetails.code) {
exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
} else if (injectDetails.file) {
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) {
// 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');
return origOpenFunc.apply(window, arguments);
}
strUrl = urlutil.makeAbsolute(strUrl);
var iab = new InAppBrowser();
callbacks = callbacks || {};
for (var callbackName in callbacks) {
iab.addEventListener(callbackName, callbacks[callbackName]);
}
var cb = function(eventname) {
iab._eventHandler(eventname);
};
strWindowFeatures = strWindowFeatures || "";
exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
return iab;
};
})();

View File

@@ -1,4 +1,4 @@
cordova.define("org.apache.cordova.inappbrowser.InAppBrowserProxy", function(require, exports, module) { /*
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -17,10 +17,10 @@ cordova.define("org.apache.cordova.inappbrowser.InAppBrowserProxy", function(req
* specific language governing permissions and limitations
* under the License.
*
*/
/*global Windows:true */
*/
/*jslint sloppy:true */
/*global Windows:true, require, document, setTimeout, window, module */
var cordova = require('cordova'),
@@ -30,27 +30,29 @@ var browserWrap;
var IAB = {
close: function (win,lose) {
close: function (win, lose) {
if (browserWrap) {
browserWrap.parentNode.removeChild(browserWrap);
browserWrap = null;
}
},
show: function (win,lose) {
if (browserWrap) {
show: function (win, lose) {
/* empty block, ran out of bacon?
if (browserWrap) {
}
}*/
},
open: function (win,lose,args) {
var strUrl = args[0];
var target = args[1];
var features = args[2];
open: function (win, lose, args) {
var strUrl = args[0],
target = args[1],
features = args[2],
url,
elem;
if (target == "_system") {
var url = new Windows.Foundation.Uri(strUrl)
if (target === "_system") {
url = new Windows.Foundation.Uri(strUrl);
Windows.System.Launcher.launchUriAsync(url);
}
else if (target == "_blank") {
} else if (target === "_blank") {
if (!browserWrap) {
browserWrap = document.createElement("div");
browserWrap.style.position = "absolute";
@@ -59,18 +61,20 @@ var IAB = {
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 elem = document.createElement("iframe");
elem.style.width = (window.innerWidth - 80)+ "px";
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";
@@ -83,9 +87,25 @@ var IAB = {
}
});
} 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 {
} else {
window.location = strUrl;
}
@@ -93,12 +113,12 @@ var IAB = {
},
injectScriptCode:function(code, bCB) {
injectScriptCode: function (code, bCB) {
// "(function(d) { var c = d.createElement('script'); c.src = %@; d.body.appendChild(c); })(document)"
},
injectScriptFile:function(file, bCB) {
injectScriptFile: function (file, bCB) {
}
};
@@ -106,4 +126,4 @@ var IAB = {
module.exports = IAB;
require("cordova/windows8/commandProxy").add("InAppBrowser",module.exports);
require("cordova/exec/proxy").add("InAppBrowser", module.exports);