init
37
CONTRIBUTING.md
Normal 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!
|
||||
202
LICENSE
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
||||
5
NOTICE
Normal 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/).
|
||||
381
README.md
Normal file
@@ -0,0 +1,381 @@
|
||||
<!---
|
||||
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-themeablebrowser
|
||||
===============================
|
||||
|
||||
**This repo is out of maintenance** due to its original mainteners are no longer able to maintain it in an acceptable fashion. Please consider forking this repo if it interests you. Apologies to everyone who still depends on this repo and thanks to everyone who has contributed.
|
||||
|
||||
---
|
||||
|
||||
This plugin is a fork of [org.apache.cordova.inappbrowser](https://github.com/apache/cordova-plugin-inappbrowser). It attempts to retain most of the features of the InAppBrowser. In fact, for the full list of features inherited from InAppBrowser, please refer to [InAppBrowser's documentation](https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md).
|
||||
|
||||
The purpose of this plugin is to provide an in-app-browser that can also be configured to match the theme of your app, in order to give it a more immersive look and feel for your app, as well as provide a more consistent look and feel across platforms.
|
||||
|
||||
This plugin launches an in-app web view on top the existing [CordovaWebView](https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaWebView.java) by calling `cordova.ThemeableBrowser.open()`.
|
||||
|
||||
// Keep in mind that you must add your own images to native resource.
|
||||
// Images below are for sample only. They are not imported by this plugin.
|
||||
cordova.ThemeableBrowser.open('http://apache.org', '_blank', {
|
||||
statusbar: {
|
||||
color: '#ffffffff'
|
||||
},
|
||||
toolbar: {
|
||||
height: 44,
|
||||
color: '#f0f0f0ff'
|
||||
},
|
||||
title: {
|
||||
color: '#003264ff',
|
||||
showPageTitle: true
|
||||
},
|
||||
backButton: {
|
||||
image: 'back',
|
||||
imagePressed: 'back_pressed',
|
||||
align: 'left',
|
||||
event: 'backPressed'
|
||||
},
|
||||
forwardButton: {
|
||||
image: 'forward',
|
||||
imagePressed: 'forward_pressed',
|
||||
align: 'left',
|
||||
event: 'forwardPressed'
|
||||
},
|
||||
closeButton: {
|
||||
image: 'close',
|
||||
imagePressed: 'close_pressed',
|
||||
align: 'left',
|
||||
event: 'closePressed'
|
||||
},
|
||||
customButtons: [
|
||||
{
|
||||
image: 'share',
|
||||
imagePressed: 'share_pressed',
|
||||
align: 'right',
|
||||
event: 'sharePressed'
|
||||
}
|
||||
],
|
||||
menu: {
|
||||
image: 'menu',
|
||||
imagePressed: 'menu_pressed',
|
||||
title: 'Test',
|
||||
cancel: 'Cancel',
|
||||
align: 'right',
|
||||
items: [
|
||||
{
|
||||
event: 'helloPressed',
|
||||
label: 'Hello World!'
|
||||
},
|
||||
{
|
||||
event: 'testPressed',
|
||||
label: 'Test!'
|
||||
}
|
||||
]
|
||||
},
|
||||
backButtonCanClose: true
|
||||
}).addEventListener('backPressed', function(e) {
|
||||
alert('back pressed');
|
||||
}).addEventListener('helloPressed', function(e) {
|
||||
alert('hello pressed');
|
||||
}).addEventListener('sharePressed', function(e) {
|
||||
alert(e.url);
|
||||
}).addEventListener(cordova.ThemeableBrowser.EVT_ERR, function(e) {
|
||||
console.error(e.message);
|
||||
}).addEventListener(cordova.ThemeableBrowser.EVT_WRN, function(e) {
|
||||
console.log(e.message);
|
||||
});
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
cordova plugin add cordova-plugin-themeablebrowser
|
||||
|
||||
Additional Properties
|
||||
---------------------
|
||||
|
||||
In addition to InAppBrowser's properties, following properties were added to fulfill this plugin's purpose in a nested JSON object.
|
||||
|
||||
+ `statusbar` applicable to only iOS 7+.
|
||||
+ `color` sets status bar color for iOS 7+ in RGBA web hex format. eg. `#fff0f0ff`. Default to white. Applicable to only iOS 7+.
|
||||
+ `toolbar`
|
||||
+ `height` sets height of toolbar. Default to 44.
|
||||
+ `color` sets browser toolbar color in RGBA web hex format. eg. `#fff0f0ff`. Default to white. Also see `image`.
|
||||
+ `image` sets an image as browser toolbar background in titled mode. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `title`
|
||||
+ `color` sets title text color in RGBA web hex format. eg. `#fff0f0ff`. Default to black.
|
||||
+ `staticText` sets static text for title. This property overrides `showPageTitle` (see below).
|
||||
+ `showPageTitle` when set to true, title of the current web page will be shown.
|
||||
+ `backButton`
|
||||
+ `image` sets image for back button. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `imagePressed` sets image for back button in its pressed state. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `align` aligns back button to either `left` or `right`. Default to `left`.
|
||||
+ `event` raises an custom event with given text as event name when back button is pressed. Optional.
|
||||
+ `forwardButton`
|
||||
+ `image` sets image for forward button. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `imagePressed` sets image for forward button in its pressed state. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `align` aligns forward button to either `left` or `right`. Default to `left`.
|
||||
+ `event` raises an custom event with given text as event name when forward button is pressed. Optional.
|
||||
+ `closeButton`
|
||||
+ `image` sets image for close button. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `imagePressed` sets image for close button in its pressed state. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `align` aligns close button to either `left` or `right`. Default to `left`.
|
||||
+ `event` raises an custom event with given text as event name when close button is pressed. Optional.
|
||||
+ `menu`
|
||||
+ `title` sets menu title when menu button is clicked. iOS only.
|
||||
+ `cancel` sets menu cancel button text. iOS only.
|
||||
+ `image` sets image for menu button. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `imagePressed` sets image for menu button in its pressed state. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `event` raises an custom event with given text as event name when menu button is pressed. Optional.
|
||||
+ `align` aligns menu button to either `left` or `right`. Default to `left`.
|
||||
+ `items` is a list of items to be shown when menu is open
|
||||
+ `event` defines the event name that will be raised when this menu item is clicked. The callbacks to menu events will receive an event object that contains the following properties: `url` is the current URL shown in browser and `index` is the index of the selected item in `items`.
|
||||
+ `label` defines the menu item label text.
|
||||
+ `customButtons` is a list of objects that will be inserted into toolbar when given.
|
||||
+ `image` sets image for custom button. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `imagePressed` sets image for custom button in its pressed state. This property references to a **native** image resource, therefore it is platform dependent.
|
||||
+ `align` aligns custom button to either `left` or `right`. Default to `left`.
|
||||
+ `event` raises an custom event with given text as event name when custom button is pressed. The callbacks to custom button events will receive an event object that contains the following properties: `url` is the current URL shown in browser and `index` is the index of the selected button in `customButtons`.
|
||||
+ `backButtonCanClose` allows back button to close browser when there's no more to go back. Otherwise, back button will be disabled.
|
||||
+ `disableAnimation` when set to true, disables browser show and close animations.
|
||||
+ `fullscreen` when set to `true`, WebView will expand to the full height of the app, going under the toolbar. This flag combined with transparent toolbar color could allow toolbar buttons to appear floating on top of the WebView. (Remember, this plugin supports RGBA color format.) Optional.
|
||||
|
||||
All properties are optional with little default values. If a property is not given, its corresponding UI element will not be shown.
|
||||
|
||||
One thing to note is that all image resources reference to **native** resource bundle. So all images need to be imported to native project first. In case of Android, the image name will be looked up under `R.drawable`. eg. If image name is `hello_world`, `R.drawable.hello_world` will be referenced.
|
||||
|
||||
You may have noticed that ThemedBrowser added an optional menu as well as custom buttons, which you can utilize to respond to some simple user actions.
|
||||
|
||||
Experimental Properties
|
||||
-----------------------
|
||||
|
||||
Followings are experimental properties that can be used in some special cases. Usage of these property are discouraged due to stability and efficiency.
|
||||
|
||||
For any object that supports `image` and `imagePressed` properties, there is a set of fallback properties that can be used when you absolutely cannot import native sources due to some circumstances.
|
||||
|
||||
+ `(\w+Button|menu|toolbar)`
|
||||
+ `wwwImage` is like `image` but loads image from Cordova's `www` directory instead. This is a fallback solution when you cannot import native resources. Use `image` property as much as possible.
|
||||
+ `wwwImagePressed` is like `image` but loads image from Cordova's `www` directory instead. This is a fallback solution when you cannot import native resources. Use `image` property as much as possible.
|
||||
+ `wwwImageDensity` is needed when `wwwImage` and/or `wwwImagePressed` are given. Since these images are not loaded from resource bundle, density is unknown, therefore density needs to set by this property. Corresponds to iOS' `@2x`, `@3x` suffix.
|
||||
|
||||
eg.
|
||||
|
||||
cordova.ThemeableBrowser.open('http://apache.org', '_blank', {
|
||||
...
|
||||
backButton: {
|
||||
wwwImage: 'images/back.png',
|
||||
wwwImagePressed: 'images/back_pressed.png',
|
||||
wwwImageDensity: 2,
|
||||
align: 'left',
|
||||
event: 'backPressed'
|
||||
}
|
||||
...
|
||||
});
|
||||
|
||||
File path is relative to `www` directory, which contains your web app sources. One thing that is very important is the `wwwImageDensity` property. Since images are not loaded from native resource bundle, density of any loaded images cannot not be automatically determined, therefore it needs to be explicity set. *You* are responsible for supplying the correct images with its corresponding density for any given device. If you don't know what image density means, please read [this documentation](https://developer.apple.com/library/ios/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/SupportingHiResScreensInViews/SupportingHiResScreensInViews.html). Ideally you are supposed to perform a device detection based on `window.devicePixelRatio` to supply optimal images. However a cheap way is to always supply high density images and rely on OS to scale down for lower screen density devices. Of course this would be inefficient, but it would save you a lot of trouble. Following is a cheatsheet that corresponds `wwwImageDensity` values to iOS and Android densities. Though `wwwImageDensity` does accept float values, followings are handy lookup.
|
||||
|
||||
| `wwwImageDensity` | iOS | Android |
|
||||
| ----------------- | ------------ | ------- |
|
||||
| 1 | *No suffix* | mdpi |
|
||||
| 2 | `@2x` | xhdpi |
|
||||
| 3 | `@3x` | xxdpi |
|
||||
| 4 | *N/A* | xxxhdpi |
|
||||
|
||||
Additional Methods
|
||||
------------------
|
||||
|
||||
The reference object returned by `cordova.ThemeableBrowser.open` contains the following methods in addition to InAppBrowser's implementation:
|
||||
|
||||
+ `reload` reloads the current page.
|
||||
|
||||
Errors and Warnings
|
||||
-------------------
|
||||
|
||||
This plugin does not want to be the source of your app crash, not to mention that you have no way to catch exceptions from native code, so it does not throw exceptions. Neither does it want to write to log, because it wants to avoid polluting your log and respect your choice of logging library. Hence all errors are warnings are reported back to you through events. You may listen to two special events defined by `cordova.ThemeableBrowser.EVT_ERR` and `cordova.ThemeableBrowser.EVT_WRN`. Upon error or warning, you will receive event object that contains the following properties:
|
||||
|
||||
+ `code` contains the error or warning code, which is defined by one of the followings:
|
||||
+ `cordova.ThemeableBrowser.ERR_CRITICAL` is raised for a critical error that you should definitely try to resolve. eg. JSON parser failure. Dialer launch failure. Raised only for `cordova.ThemeableBrowser.EVT_ERR` event.
|
||||
+ `cordova.ThemeableBrowser.ERR_LOADFAIL` is raised when a native image that you referenced in your config failed to load from native resource bundle. Raised only for `cordova.ThemeableBrowser.EVT_ERR` event.
|
||||
+ `cordova.ThemeableBrowser.WRN_UNDEFINED` is raised when a property in your config is not defined. You will not get this warning for every property that is undefined, just the ones that might cause confusion. Raised only for `cordova.ThemeableBrowser.EVT_WRN` event.
|
||||
+ `cordova.ThemeableBrowser.WRN_UNEXPECTED` is raised when an unexpected behaviour is committed. You can ignore this warning, since such behaviours will be simply ignored. eg. Try to close the browser when it's already closed. Raised only for `cordova.ThemeableBrowser.EVT_WRN` event.
|
||||
+ `message` contains a readable message that will try its best to tell you want went wrong.
|
||||
|
||||
Examples:
|
||||
|
||||
cordova.ThemeableBrowser.open('http://apache.org', '_blank', {
|
||||
...
|
||||
}).addEventListener(cordova.ThemeableBrowser.EVT_ERR, function(e) {
|
||||
if (e.code === cordova.ThemeableBrowser.ERR_CRITICAL) {
|
||||
// TODO: Handle critical error.
|
||||
} else if (e.code === cordova.ThemeableBrowser.ERR_LOADFAIL) {
|
||||
// TODO: Image failed to load.
|
||||
}
|
||||
|
||||
console.error(e.message);
|
||||
}).addEventListener(cordova.ThemeableBrowser.EVT_WRN, function(e) {
|
||||
if (e.code === cordova.ThemeableBrowser.WRN_UNDEFINED) {
|
||||
// TODO: Some property undefined in config.
|
||||
} else if (e.code === cordova.ThemeableBrowser.WRN_UNEXPECTED) {
|
||||
// TODO: Something strange happened. But no big deal.
|
||||
}
|
||||
|
||||
console.log(e.message);
|
||||
});
|
||||
|
||||
These events are intended to help you debug strange behaviours. So if you run into something weird, please listene to these events and it might just tell you what's wrong. Please note errors and warnings are not completely consistent across platforms. There are some minor platform differences.
|
||||
|
||||
Import Native Images
|
||||
--------------------
|
||||
|
||||
If you are a native developer and are already aware how to import native image resources, feel free to skip this section. Otherwise, here are some tips. First of all, your native iOS and Android projects are located at:
|
||||
|
||||
<cordova_project_root>/platforms/ios
|
||||
<cordova_project_root>/platforms/android
|
||||
|
||||
Let's start with Android, which is quite straightforward. Prepare your images for all of the pixel densities that you'd like to support. [Here is a documentation](http://developer.android.com/guide/practices/screens_support.html) that explains this concept. The gist is that on higher pixel density screens, your images will have to have higher resolution in order to look sharp on an actual device, so you want to prepare multiple files for the same image at different resolutions for their respective pixel density. In Android, there are a lot of densities due to diversity of devices, so you have to decide which ones you want to support. Fortunately if you don't have an image for a particular pixel density, Android will automatically pick up the closest one and try to down scale or up scale it. Of course this process is not very efficient, so you have to make your decisions. The directory where you want to place your images are under
|
||||
|
||||
<cordova_project_root>/platforms/android/res
|
||||
|
||||
Notice how there are multiple folders named `drawble-.*`. Each file for the same image should be named the same, but it will need to be moved under the correct directory with respect to its target density. eg. If `icon.png` is intended for xhdpi, then it needs to go under `drawable-xhdpi` directory. In your JavaScript config, you can then reference to this iamge without extension. eg. With the previous example, simply `icon` will suffice.
|
||||
|
||||
To import image resources for iOS, it is slightly trickier, because you **have** to register your file in Xcode project file with help from Xcode, and there are two ways of doing this. Let's start with the old school way. iOS also shares similar concept with Android in terms of pixel density. iPhone to iPhone 3GS uses 1x the resolution, iPhone 4 to iPhone 6 uses 2x the resolution while iPhone 6 Plus and above uses 3x the resolution (even though it's actually down scaled, but that's a different discussion). In the old school way, you have to name your images with `@1x`, `@2x`, and `@3x` suffix with respect to their target density. eg. `icon@2x.png`. [Here is a documentation](https://developer.apple.com/library/ios/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/SupportingHiResScreensInViews/SupportingHiResScreensInViews.html) that explains this concept. You then have to move it under
|
||||
|
||||
<cordova_project_root>/platforms/ios/<project_name>/Resources
|
||||
|
||||
Then open your native iOS project with Xcode by double clicking on
|
||||
|
||||
<cordova_project_root>/platforms/ios/<project_name>.xcodeproj
|
||||
|
||||
In the left hand side panel, make sure you are in Project navigator tab. Then you can see a list of directories under your project. One of them being `Resources`, but you don't see your newly added images there. Now you need to drag your images fron Finder to Xcode and drop it under `Resource` folder. In your JavaScript config, you can then reference to them without suffix or extension. eg. With the previous example, simply `icon` will suffice.
|
||||
|
||||
The new school way is to use [Asset Catalog](https://developer.apple.com/library/ios/recipes/xcode_help-image_catalog-1.0/Recipe.html). This is the recommended technique from Xcode 5+ and iOS 7+. It gives you better management of all of your image resources. ie. No more suffix, and you can see all your images for different densities in one table etc. However there are more steps involved to set it up. Please reference to [this guide](http://www.intertech.com/Blog/xcode-assets-xcassets/) for a step by step walkthrough.
|
||||
|
||||
If for some reason you absolutely cannot import native images, you may consider using the `wwwImage`, `wwwImagePressed` and `wwwImageDensity` properties as fallback solution, though this is an experimental feature and is discouraged. See [above](#experimental-properties) for documentation.
|
||||
|
||||
FAQ
|
||||
---
|
||||
|
||||
### I just installed this plugin, how come it just shows a blank toolbar?
|
||||
|
||||
The purpose of this plugin is to allow **you** to style the in app browser the way you want. Isn't that why you installed this plugin in the first place? Hence, it does not come with any defaults. Every UI element needs to be styled by you, otherwise it's hidden. This also avoids polluting your resouce bundle with default images.
|
||||
|
||||
### Why does my menu on Android look ugly?
|
||||
|
||||
Android menu is simply a [Spinner](http://developer.android.com/guide/topics/ui/controls/spinner.html), which picks up its style from your Activity's theme. By default Cordova uses the very old [Theme.Black.NoTitleBar](http://developer.android.com/reference/android/R.style.html#Theme_Black_NoTitleBar), which is ugly. Open your AndroidManifest.xml and change your `android:theme` attribute to something more morden, such as [Theme.Holo](http://developer.android.com/reference/android/R.style.html#Theme_Holo) or [Base.Theme.AppCompat](http://developer.android.com/reference/android/support/v7/appcompat/R.style.html#Base_Theme_AppCompat) from [support library](https://developer.android.com/tools/support-library/features.html#v7-appcompat).
|
||||
|
||||
### How do I style Android menu?
|
||||
|
||||
Android menu is simply a [Spinner](http://developer.android.com/guide/topics/ui/controls/spinner.html) with default layout resources, which picks up its style from your Activity's theme. You can style it by making a theme of your app and apply it to your activity. See `android:dropDownListViewStyle`.
|
||||
|
||||
### How do I add margings and paddings?
|
||||
|
||||
There is no margins or paddings. However notice that you can assign images to each of the buttons. So take advantage of PNG's transparency to create margins/paddings around your buttons.
|
||||
|
||||
### How do I add shadow to the toolbar?
|
||||
|
||||
First, notice that you can use an image as well as color for toolbar background. Use PNG for background image and create shadow inside this image. Next, you will probably be concerned about how buttons will slightly misaligned due since they always middle align. Again create some transparent borders in your button images to offset the misalignment. eg. Say your shadow is 5px tall, which causes buttons to allear lower than they shoud. Create a 10px transparent bottom border for each of your button icons and you are set.
|
||||
|
||||
Supported Platforms
|
||||
-------------------
|
||||
|
||||
+ iOS 5.0+
|
||||
+ Android 2.0+
|
||||
|
||||
Currently there is no plan to support other platforms, though source code from InAppBrowser is kept for merge purposes, they are inactive, since they are removed from `plugin.xml`.
|
||||
|
||||
Migration
|
||||
---------
|
||||
|
||||
This plugin is **not** a drop-in replacement for InAppBrowser. The biggest change that was made from InAppBrowser, which caused it to be no longer compatible with InAppBrowser's API is that `options` parameter now accepts a JavaScript object instead of string.
|
||||
|
||||
cordova.ThemeableBrowser.open('http://apache.org', '_blank', {
|
||||
customButtons: [
|
||||
{
|
||||
image: 'share',
|
||||
imagePressed: 'share_pressed',
|
||||
align: 'right',
|
||||
event: 'sharePressed'
|
||||
}
|
||||
],
|
||||
menu: {
|
||||
image: 'menu',
|
||||
imagePressed: 'menu_pressed',
|
||||
items: [
|
||||
{
|
||||
event: 'helloPressed',
|
||||
label: 'Hello World!'
|
||||
},
|
||||
{
|
||||
event: 'testPressed',
|
||||
label: 'Test!'
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
As you can see from above, this allows configurations to have more robust and readable definition.
|
||||
|
||||
Furthermore, the object returned by `open` always returns its own instance allowing chaining of methods. Obviously, this breaks the immitation of `window.open()`, however it's an optional feature that you can choose not to use if you want to stay loyal to the original.
|
||||
|
||||
cordova.ThemeableBrowser.open('http://apache.org', '_blank', {
|
||||
customButtons: [
|
||||
{
|
||||
image: 'share',
|
||||
imagePressed: 'share_pressed',
|
||||
align: 'right',
|
||||
event: 'sharePressed'
|
||||
}
|
||||
],
|
||||
menu: {
|
||||
image: 'menu',
|
||||
imagePressed: 'menu_pressed',
|
||||
items: [
|
||||
{
|
||||
event: 'helloPressed',
|
||||
label: 'Hello World!'
|
||||
},
|
||||
{
|
||||
event: 'testPressed',
|
||||
label: 'Test!'
|
||||
}
|
||||
]
|
||||
}
|
||||
}).addEventListener('sharePressed', function(event) {
|
||||
alert(event.url);
|
||||
}).addEventListener('helloPressed', function(event) {
|
||||
alert(event.url);
|
||||
}).addEventListener('testPressed', function(event) {
|
||||
alert(event.url);
|
||||
});
|
||||
|
||||
Two properties from InAppBrowser are disabled.
|
||||
+ `location` is always `false` because address bar is not needed for an immersive experience of an integrated browser.
|
||||
+ `toolbarposition` is always `top` to remain consistent across platforms.
|
||||
|
||||
One is redefined.
|
||||
+ `toolbar` is redefined to contain toolbar settings and toolbar is always shown, because the whole point why you are using this plugin is to style toolbar right?
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
This project is licensed under Aapache License 2.0. See [LICENSE](LICENSE) file.
|
||||
125
RELEASENOTES.md
Normal file
@@ -0,0 +1,125 @@
|
||||
<!--
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
-->
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
0.2.17
|
||||
------
|
||||
|
||||
Bug fix: remove hardcoded density value and add correct param
|
||||
Bug fix: Open iTunes Store links in AppStore app for iOS
|
||||
|
||||
0.2.15
|
||||
------
|
||||
|
||||
Bug fix: fixes typo
|
||||
|
||||
0.2.14
|
||||
------
|
||||
|
||||
Bug fix for: not building in cordova 6.0.0 cordova-ios 4.0+
|
||||
Note: you might need to update the <allow-navigation> in config.xml for cordova 6.0+
|
||||
|
||||
0.2.13
|
||||
------
|
||||
|
||||
Bug fix for: Fix for ERR_UNKNOWN_URL_SCHEME for common URL scms
|
||||
|
||||
|
||||
0.2.12
|
||||
------
|
||||
|
||||
Bug fixes.
|
||||
|
||||
0.2.11
|
||||
------
|
||||
|
||||
Expanded wwwImage feature to toolbar.
|
||||
|
||||
0.2.10
|
||||
------
|
||||
|
||||
Added a experimental feature to allow loading images from assets instead of native resources.
|
||||
|
||||
0.2.9
|
||||
-----
|
||||
|
||||
Bug fixes.
|
||||
|
||||
0.2.8
|
||||
-----
|
||||
|
||||
No functional change. Migrated to npm as per Cordova's direction.
|
||||
|
||||
0.2.7
|
||||
-----
|
||||
|
||||
Bug fixes. Merged changes from upstream (InAppBrowser). Added fullscreen feature.
|
||||
|
||||
0.2.6
|
||||
-----
|
||||
|
||||
Bug fixes.
|
||||
|
||||
0.2.5
|
||||
-----
|
||||
|
||||
Bug fixes.
|
||||
|
||||
0.2.4
|
||||
-----
|
||||
|
||||
Added a reload feature. Better iOS implementation to improve backward compatibility and reduce the amount of hacks.
|
||||
|
||||
0.2.3
|
||||
-----
|
||||
|
||||
Bug fixes.
|
||||
|
||||
0.2.2
|
||||
-----
|
||||
|
||||
Added error and warning reporting capabilities. Added property to disable animation.
|
||||
|
||||
0.2.1
|
||||
-----
|
||||
|
||||
Debug and stablization.
|
||||
|
||||
0.2.0
|
||||
-----
|
||||
|
||||
Major improvement and resign of API to make it much more powerful and elegant.
|
||||
|
||||
0.1.2
|
||||
-----
|
||||
|
||||
No code change was made. Legacy doc was moved to prevent Cordova plugin registry from picking them up.
|
||||
|
||||
0.1.1
|
||||
-----
|
||||
|
||||
No code change was made. Doc was updated. Version number was updated because plugman wouldn't publish the 1.0.
|
||||
|
||||
0.1
|
||||
---
|
||||
|
||||
Initial release.
|
||||
BIN
doc/images/android_menu_sample_01.png
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
doc/images/android_sample_01.png
Normal file
|
After Width: | Height: | Size: 48 KiB |
BIN
doc/images/ios_menu_sample_01.png
Normal file
|
After Width: | Height: | Size: 43 KiB |
BIN
doc/images/ios_sample_01.png
Normal file
|
After Width: | Height: | Size: 50 KiB |
1
legacy_doc/README.md
Normal file
@@ -0,0 +1 @@
|
||||
This directory is deprecated. It contains legacy files from [InAppBrowser](https://github.com/apache/cordova-plugin-inappbrowser). They are kept here to make potential merge and/or pull easier and keep better track of file histories.
|
||||
357
legacy_doc/de/index.md
Normal 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"});
|
||||
});
|
||||
357
legacy_doc/es/index.md
Normal 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"});
|
||||
});
|
||||
357
legacy_doc/fr/index.md
Normal 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"});
|
||||
});
|
||||
357
legacy_doc/it/index.md
Normal 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"});
|
||||
});
|
||||
357
legacy_doc/ja/index.md
Normal 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"});
|
||||
});
|
||||
357
legacy_doc/ko/index.md
Normal 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"});
|
||||
});
|
||||
357
legacy_doc/pl/index.md
Normal 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
legacy_doc/ru/index.md
Normal 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"});
|
||||
});
|
||||
357
legacy_doc/zh/index.md
Normal 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"});
|
||||
});
|
||||
73
package.json
Normal file
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"_from": "cordova-plugin-themeablebrowser",
|
||||
"_id": "cordova-plugin-themeablebrowser@0.2.18",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-IBvfFEHJb4tovZyjOcbv18xoCbQ=",
|
||||
"_location": "/cordova-plugin-themeablebrowser",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "tag",
|
||||
"registry": true,
|
||||
"raw": "cordova-plugin-themeablebrowser",
|
||||
"name": "cordova-plugin-themeablebrowser",
|
||||
"escapedName": "cordova-plugin-themeablebrowser",
|
||||
"rawSpec": "",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "latest"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"#USER",
|
||||
"/"
|
||||
],
|
||||
"_resolved": "https://registry.npm.taobao.org/cordova-plugin-themeablebrowser/download/cordova-plugin-themeablebrowser-0.2.18.tgz",
|
||||
"_shasum": "201bdf1441c96f8b68bd9ca339c6efd7cc6809b4",
|
||||
"_spec": "cordova-plugin-themeablebrowser",
|
||||
"_where": "C:\\Users\\moneyinto\\Desktop\\projects\\ionicTest",
|
||||
"author": {
|
||||
"name": "Apache Software Foundation"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/initialxy/cordova-plugin-themeablebrowser/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"cordova": {
|
||||
"id": "cordova-plugin-themeablebrowser",
|
||||
"platforms": [
|
||||
"android",
|
||||
"amazon-fireos",
|
||||
"ubuntu",
|
||||
"ios",
|
||||
"wp7",
|
||||
"wp8",
|
||||
"windows8",
|
||||
"windows",
|
||||
"firefoxos"
|
||||
]
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Cordova ThemeableBrowser Plugin",
|
||||
"engines": [
|
||||
{
|
||||
"name": "cordova",
|
||||
"version": ">=3.1.0"
|
||||
}
|
||||
],
|
||||
"homepage": "https://github.com/initialxy/cordova-plugin-themeablebrowser#readme",
|
||||
"keywords": [
|
||||
"cordova",
|
||||
"in",
|
||||
"app",
|
||||
"browser",
|
||||
"themeablebrowser",
|
||||
"ecosystem:cordova",
|
||||
"cordova-android",
|
||||
"cordova-ios"
|
||||
],
|
||||
"license": "Apache 2.0",
|
||||
"name": "cordova-plugin-themeablebrowser",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/initialxy/cordova-plugin-themeablebrowser.git"
|
||||
},
|
||||
"version": "0.2.18"
|
||||
}
|
||||
74
plugin.xml
Normal file
@@ -0,0 +1,74 @@
|
||||
<?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-themeablebrowser"
|
||||
version="0.2.17">
|
||||
|
||||
<name>ThemeableBrowser</name>
|
||||
<description>Cordova ThemeableBrowser Plugin</description>
|
||||
<license>Apache 2.0</license>
|
||||
<keywords>cordova,in,app,browser,themeablebrowser</keywords>
|
||||
<repo>https://github.com/initialxy/cordova-plugin-themeablebrowser.git</repo>
|
||||
<issue>https://github.com/initialxy/cordova-plugin-themeablebrowser/issues</issue>
|
||||
|
||||
<engines>
|
||||
<engine name="cordova" version=">=3.1.0" />
|
||||
</engines>
|
||||
|
||||
<!-- android -->
|
||||
<platform name="android">
|
||||
<js-module src="www/themeablebrowser.js" name="themeablebrowser">
|
||||
<clobbers target="cordova.ThemeableBrowser" />
|
||||
</js-module>
|
||||
<config-file target="res/xml/config.xml" parent="/*">
|
||||
<feature name="ThemeableBrowser">
|
||||
<param name="android-package" value="com.initialxy.cordova.themeablebrowser.ThemeableBrowser"/>
|
||||
</feature>
|
||||
</config-file>
|
||||
|
||||
<source-file src="src/android/ThemeableBrowser.java" target-dir="src/com/initialxy/cordova/themeablebrowser" />
|
||||
<source-file src="src/android/ThemeableBrowserDialog.java" target-dir="src/com/initialxy/cordova/themeablebrowser" />
|
||||
<source-file src="src/android/InAppChromeClient.java" target-dir="src/com/initialxy/cordova/themeablebrowser" />
|
||||
<source-file src="src/android/ThemeableBrowserUnmarshaller.java" target-dir="src/com/initialxy/cordova/themeablebrowser" />
|
||||
<source-file src="src/android/VideoEnabledWebChromeClient.java" target-dir="src/com/initialxy/cordova/themeablebrowser" />
|
||||
<source-file src="src/android/VideoEnabledWebView.java" target-dir="src/com/initialxy/cordova/themeablebrowser" />
|
||||
</platform>
|
||||
|
||||
<!-- ios -->
|
||||
<platform name="ios">
|
||||
<js-module src="www/themeablebrowser.js" name="themeablebrowser">
|
||||
<clobbers target="cordova.ThemeableBrowser" />
|
||||
</js-module>
|
||||
<config-file target="config.xml" parent="/*">
|
||||
<feature name="ThemeableBrowser">
|
||||
<param name="ios-package" value="CDVThemeableBrowser" />
|
||||
</feature>
|
||||
</config-file>
|
||||
|
||||
<header-file src="src/ios/CDVThemeableBrowser.h" />
|
||||
<source-file src="src/ios/CDVThemeableBrowser.m" />
|
||||
<header-file src="src/ios/CDVWKThemeableBrowserUIDelegate.h" />
|
||||
<source-file src="src/ios/CDVWKThemeableBrowserUIDelegate.m" />
|
||||
|
||||
<framework src="CoreGraphics.framework" />
|
||||
</platform>
|
||||
</plugin>
|
||||
846
src/amazon/InAppBrowser.java
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
146
src/amazon/InAppChromeClient.java
Normal 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;
|
||||
}
|
||||
|
||||
}
|
||||
133
src/android/InAppChromeClient.java
Normal file
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
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 com.initialxy.cordova.themeablebrowser;
|
||||
|
||||
import org.apache.cordova.CordovaWebView;
|
||||
import org.apache.cordova.LOG;
|
||||
import org.apache.cordova.PluginResult;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.webkit.JsPromptResult;
|
||||
import android.webkit.WebChromeClient;
|
||||
import android.webkit.WebStorage;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.GeolocationPermissions.Callback;
|
||||
|
||||
public class InAppChromeClient extends WebChromeClient {
|
||||
|
||||
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, WebStorage.QuotaUpdater quotaUpdater)
|
||||
{
|
||||
LOG.d(LOG_TAG, "onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
|
||||
quotaUpdater.updateQuota(MAX_QUOTA);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 ThemeableBrowser is capable of executing any
|
||||
* oustanding callback belonging to the ThemeableBrowser 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 "ThemeableBrowser0123456789")
|
||||
*
|
||||
* 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(WebView view, String url, String message, String defaultValue, JsPromptResult 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("ThemeableBrowser")) {
|
||||
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, "ThemeableBrowser does not support Cordova API calls: " + url + " " + defaultValue);
|
||||
result.cancel();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
1574
src/android/ThemeableBrowser.java
Normal file
61
src/android/ThemeableBrowserDialog.java
Normal file
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
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 com.initialxy.cordova.themeablebrowser;
|
||||
|
||||
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 ThemeableBrowserDialog extends Dialog {
|
||||
Context context;
|
||||
ThemeableBrowser themeableBrowser = null;
|
||||
boolean hardwareBack;
|
||||
|
||||
public ThemeableBrowserDialog(Context context, int theme,
|
||||
boolean hardwareBack) {
|
||||
super(context, theme);
|
||||
this.context = context;
|
||||
this.hardwareBack = hardwareBack;
|
||||
}
|
||||
|
||||
public void setThemeableBrowser(ThemeableBrowser browser) {
|
||||
this.themeableBrowser = browser;
|
||||
}
|
||||
|
||||
public void onBackPressed () {
|
||||
if (this.themeableBrowser == null) {
|
||||
this.dismiss();
|
||||
} else {
|
||||
// better to go through in themeableBrowser because it does a clean
|
||||
// up
|
||||
if (this.hardwareBack && this.themeableBrowser.canGoBack()) {
|
||||
this.themeableBrowser.goBack();
|
||||
} else {
|
||||
this.themeableBrowser.closeDialog();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
423
src/android/ThemeableBrowserUnmarshaller.java
Normal file
@@ -0,0 +1,423 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package com.initialxy.cordova.themeablebrowser;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.GenericArrayType;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This is a simple and half decent JSON to POJO unmarshaller inspired by
|
||||
* Jackson. It is only a unmarshaller without a marshaller. It is intended to
|
||||
* parse JSON passed to a plugin as options to a POJO. It is nowhere as powerful
|
||||
* as Jackson is, but for most use cases, it will do a pretty decent job since
|
||||
* it is designed to be used for general purpose unmarshalling. This avoid
|
||||
* having to import Jackson or JAXB for merely a Cordova plugin. ~350 lines
|
||||
* isn't too big right?
|
||||
*/
|
||||
public class ThemeableBrowserUnmarshaller {
|
||||
/**
|
||||
* Runtime exception to notify type mismatch between expected class
|
||||
* structure and JSON.
|
||||
*/
|
||||
public static class TypeMismatchException extends RuntimeException {
|
||||
public TypeMismatchException(Type expected, Type got) {
|
||||
super(String.format("Expected %s but got %s.", expected, got));
|
||||
}
|
||||
|
||||
public TypeMismatchException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime exception to notify errors during class initialization.
|
||||
*/
|
||||
public static class ClassInstantiationException extends RuntimeException {
|
||||
public ClassInstantiationException(Class<?> cls) {
|
||||
super(String.format("Failed to instantiate %s", cls));
|
||||
}
|
||||
|
||||
public ClassInstantiationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime exception to notify parser errors.
|
||||
*/
|
||||
public static class ParserException extends RuntimeException {
|
||||
public ParserException(Exception e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a JSON string, unmarhall it to an instance of the given class.
|
||||
*
|
||||
* @param json JSON string to unmarshall.
|
||||
* @param cls Return an instance of this class. Must be either public class
|
||||
* or private static class. Inner class will not work.
|
||||
* @param <T> Same type as cls.
|
||||
* @return An instance of class given by cls.
|
||||
* @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException
|
||||
*/
|
||||
public static <T> T JSONToObj(String json, Class<T> cls) {
|
||||
T result = null;
|
||||
|
||||
if (json != null && !json.isEmpty()) {
|
||||
try {
|
||||
JSONObject jsonObj = new JSONObject(json);
|
||||
result = JSONToObj(jsonObj, cls);
|
||||
} catch (JSONException e) {
|
||||
throw new ParserException(e);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a JSONObject, unmarhall it to an instance of the given class.
|
||||
*
|
||||
* @param jsonObj JSON string to unmarshall.
|
||||
* @param cls Return an instance of this class. Must be either public class
|
||||
* or private static class. Inner class will not work.
|
||||
* @param <T> Same type as cls.
|
||||
* @return An instance of class given by cls.
|
||||
* @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException
|
||||
*/
|
||||
public static <T> T JSONToObj(JSONObject jsonObj, Class<T> cls) {
|
||||
T result = null;
|
||||
|
||||
try {
|
||||
Constructor<T> constructor = cls.getDeclaredConstructor();
|
||||
constructor.setAccessible(true);
|
||||
result = (T) constructor.newInstance();
|
||||
Iterator<?> i = jsonObj.keys();
|
||||
|
||||
while (i.hasNext()) {
|
||||
String k = (String) i.next();
|
||||
Object val = jsonObj.get(k);
|
||||
|
||||
try {
|
||||
Field field = cls.getField(k);
|
||||
Object converted = valToType(val, field.getGenericType());
|
||||
|
||||
if (converted == null) {
|
||||
if (!field.getType().isPrimitive()) {
|
||||
field.set(result, null);
|
||||
} else {
|
||||
throw new TypeMismatchException(String.format(
|
||||
"Type %s cannot be set to null.",
|
||||
field.getType()));
|
||||
}
|
||||
} else {
|
||||
if (converted instanceof List
|
||||
&& field.getType()
|
||||
.isAssignableFrom(List.class)) {
|
||||
// Class can define their own favorite
|
||||
// implementation of List. In which case the field
|
||||
// still need to be defined as List, but it can be
|
||||
// initialized with a placeholder instance of any of
|
||||
// the List implementations (eg. ArrayList).
|
||||
Object existing = field.get(result);
|
||||
if (existing != null) {
|
||||
((List<?>) existing).clear();
|
||||
|
||||
// Just because I don't want javac to complain
|
||||
// about unsafe operations. So I'm gonna use
|
||||
// more reflection, HA!
|
||||
Method addAll = existing.getClass()
|
||||
.getMethod("addAll", Collection.class);
|
||||
addAll.invoke(existing, converted);
|
||||
} else {
|
||||
field.set(result, converted);
|
||||
}
|
||||
} else {
|
||||
field.set(result, converted);
|
||||
}
|
||||
}
|
||||
} catch (NoSuchFieldException e) {
|
||||
// Ignore.
|
||||
} catch (IllegalAccessException e) {
|
||||
// Ignore.
|
||||
} catch (IllegalArgumentException e) {
|
||||
// Ignore.
|
||||
}
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
throw new ParserException(e);
|
||||
} catch (NoSuchMethodException e) {
|
||||
throw new ClassInstantiationException(
|
||||
"Failed to retrieve constructor for "
|
||||
+ cls.toString() + ", make sure it's not an inner class.");
|
||||
} catch (InstantiationException e) {
|
||||
throw new ClassInstantiationException(cls);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new ClassInstantiationException(cls);
|
||||
} catch (InvocationTargetException e) {
|
||||
throw new ClassInstantiationException(cls);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an object extracted from JSONObject field, convert it to an
|
||||
* appropriate object with type appropriate for given type so that it can be
|
||||
* assigned to the associated field of the ummarshalled object. eg.
|
||||
* JSONObject value from a JSONObject field probably needs to be
|
||||
* unmarshalled to a class instance. Double from JSONObject may need to be
|
||||
* converted to Float. etc.
|
||||
*
|
||||
* @param val Value extracted from JSONObject field.
|
||||
* @param genericType Type to convert to. Must be generic type. ie. From
|
||||
* field.getGenericType().
|
||||
* @return Object of the given type so it can be assinged to field with
|
||||
* field.set().
|
||||
* @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException
|
||||
*/
|
||||
private static Object valToType(Object val, Type genericType) {
|
||||
Object result = null;
|
||||
boolean isArray = false;
|
||||
|
||||
Class<?> rawType = null;
|
||||
if (genericType instanceof ParameterizedType) {
|
||||
rawType = (Class<?>) ((ParameterizedType) genericType).getRawType();
|
||||
} else if (genericType instanceof GenericArrayType) {
|
||||
rawType = List.class;
|
||||
isArray = true;
|
||||
} else {
|
||||
rawType = (Class<?>) genericType;
|
||||
}
|
||||
|
||||
isArray = isArray || rawType.isArray();
|
||||
|
||||
if (val != null && val != JSONObject.NULL) {
|
||||
if (rawType.isAssignableFrom(String.class)) {
|
||||
if (val instanceof String) {
|
||||
result = val;
|
||||
} else {
|
||||
throw new TypeMismatchException(rawType, val.getClass());
|
||||
}
|
||||
} else if (isPrimitive(rawType)) {
|
||||
result = convertToPrimitiveFieldObj(val, rawType);
|
||||
} else if (isArray || rawType.isAssignableFrom(List.class)) {
|
||||
if (val instanceof JSONArray) {
|
||||
Type itemType = getListItemType(genericType);
|
||||
result = JSONToList((JSONArray) val, itemType);
|
||||
|
||||
if (isArray) {
|
||||
List<?> list = (List<?>) result;
|
||||
|
||||
Class<?> itemClass = null;
|
||||
if (itemType instanceof ParameterizedType) {
|
||||
itemClass = (Class<?>) ((ParameterizedType) itemType).getRawType();
|
||||
} else {
|
||||
itemClass = (Class<?>) itemType;
|
||||
}
|
||||
|
||||
result = Array.newInstance(itemClass, list.size());
|
||||
int cnt = 0;
|
||||
for (Object i : list) {
|
||||
Array.set(result, cnt, i);
|
||||
cnt += 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new TypeMismatchException(
|
||||
JSONArray.class, val.getClass());
|
||||
}
|
||||
} else if (val instanceof JSONObject) {
|
||||
result = JSONToObj((JSONObject) val, rawType);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a generic type representing a List or array, retrieve list or array
|
||||
* item type.
|
||||
*
|
||||
* @param type
|
||||
* @return
|
||||
*/
|
||||
private static Type getListItemType(Type type) {
|
||||
Type result = null;
|
||||
|
||||
if (type instanceof GenericArrayType) {
|
||||
result = ((GenericArrayType) type).getGenericComponentType();
|
||||
} else if (type instanceof ParameterizedType){
|
||||
result = ((ParameterizedType) type).getActualTypeArguments()[0];
|
||||
} else {
|
||||
result = ((Class<?>) type).getComponentType();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an JSONArray retrieved from JSONObject, and the destination item
|
||||
* type, unmarshall this list to a List of given item type.
|
||||
*
|
||||
* @param jsonArr
|
||||
* @param itemType
|
||||
* @return
|
||||
*/
|
||||
private static List<?> JSONToList(JSONArray jsonArr, Type itemType) {
|
||||
List<Object> result = new ArrayList<Object>();
|
||||
|
||||
Class<?> rawType = null;
|
||||
ParameterizedType pType = null;
|
||||
|
||||
if (itemType instanceof ParameterizedType) {
|
||||
pType = (ParameterizedType) itemType;
|
||||
rawType = (Class<?>) pType.getRawType();
|
||||
} else {
|
||||
rawType = (Class<?>) itemType;
|
||||
}
|
||||
|
||||
int len = jsonArr.length();
|
||||
for (int i = 0; i < len; i++) {
|
||||
try {
|
||||
Object item = jsonArr.get(i);
|
||||
Object converted = valToType(item, itemType);
|
||||
if (converted != null) {
|
||||
result.add(converted);
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
throw new ParserException(e);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if given class is one of the primitive types or more importantly,
|
||||
* one of the classes associated with a primitive type. eg. Integer, Double
|
||||
* etc.
|
||||
*
|
||||
* @param cls
|
||||
* @return
|
||||
*/
|
||||
private static boolean isPrimitive(Class<?> cls) {
|
||||
return cls.isPrimitive()
|
||||
|| cls.isAssignableFrom(Byte.class)
|
||||
|| cls.isAssignableFrom(Short.class)
|
||||
|| cls.isAssignableFrom(Integer.class)
|
||||
|| cls.isAssignableFrom(Long.class)
|
||||
|| cls.isAssignableFrom(Float.class)
|
||||
|| cls.isAssignableFrom(Double.class)
|
||||
|| cls.isAssignableFrom(Boolean.class)
|
||||
|| cls.isAssignableFrom(Character.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gracefully convert given Object to given class given the precondition
|
||||
* that both are primitives or one of the classes associated with
|
||||
* primitives. eg. If val is of type Double and cls is of type int, return
|
||||
* Integer type with appropriate value truncation so that it can be assigned
|
||||
* to field with field.set().
|
||||
*
|
||||
* @param cls
|
||||
* @param val
|
||||
* @return
|
||||
* @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException
|
||||
*/
|
||||
private static Object convertToPrimitiveFieldObj(Object val, Class<?> cls) {
|
||||
Class<?> valClass = val.getClass();
|
||||
Object result = null;
|
||||
|
||||
try {
|
||||
Method getter = null;
|
||||
if (cls.isAssignableFrom(Byte.class)
|
||||
|| cls.isAssignableFrom(Byte.TYPE)) {
|
||||
getter = valClass.getMethod("byteValue");
|
||||
} else if (cls.isAssignableFrom(Short.class)
|
||||
|| cls.isAssignableFrom(Short.TYPE)) {
|
||||
getter = valClass.getMethod("shortValue");
|
||||
} else if (cls.isAssignableFrom(Integer.class)
|
||||
|| cls.isAssignableFrom(Integer.TYPE)) {
|
||||
getter = valClass.getMethod("intValue");
|
||||
} else if (cls.isAssignableFrom(Long.class)
|
||||
|| cls.isAssignableFrom(Long.TYPE)) {
|
||||
getter = valClass.getMethod("longValue");
|
||||
} else if (cls.isAssignableFrom(Float.class)
|
||||
|| cls.isAssignableFrom(Float.TYPE)) {
|
||||
getter = valClass.getMethod("floatValue");
|
||||
} else if (cls.isAssignableFrom(Double.class)
|
||||
|| cls.isAssignableFrom(Double.TYPE)) {
|
||||
getter = valClass.getMethod("doubleValue");
|
||||
} else if (cls.isAssignableFrom(Boolean.class)
|
||||
|| cls.isAssignableFrom(Boolean.TYPE)) {
|
||||
if (val instanceof Boolean) {
|
||||
result = val;
|
||||
} else {
|
||||
throw new TypeMismatchException(cls, val.getClass());
|
||||
}
|
||||
} else if (cls.isAssignableFrom(Character.class)
|
||||
|| cls.isAssignableFrom(Character.TYPE)) {
|
||||
if (val instanceof String && ((String) val).length() == 1) {
|
||||
char c = ((String) val).charAt(0);
|
||||
result = Character.valueOf(c);
|
||||
} else if (val instanceof String) {
|
||||
throw new TypeMismatchException(
|
||||
"Expected Character, "
|
||||
+ "but received String with length other than 1.");
|
||||
} else {
|
||||
throw new TypeMismatchException(String.format(
|
||||
"Expected Character, accept String, but got %s.",
|
||||
val.getClass()));
|
||||
}
|
||||
}
|
||||
|
||||
if (getter != null) {
|
||||
result = getter.invoke(val);
|
||||
}
|
||||
} catch (NoSuchMethodException e) {
|
||||
throw new TypeMismatchException(String.format(
|
||||
"Cannot convert %s to %s.", val.getClass(), cls));
|
||||
} catch (SecurityException e) {
|
||||
throw new TypeMismatchException(String.format(
|
||||
"Cannot convert %s to %s.", val.getClass(), cls));
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new TypeMismatchException(String.format(
|
||||
"Cannot convert %s to %s.", val.getClass(), cls));
|
||||
} catch (InvocationTargetException e) {
|
||||
throw new TypeMismatchException(String.format(
|
||||
"Cannot convert %s to %s.", val.getClass(), cls));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
294
src/android/VideoEnabledWebChromeClient.java
Normal file
@@ -0,0 +1,294 @@
|
||||
package com.initialxy.cordova.themeablebrowser;
|
||||
|
||||
import android.media.MediaPlayer;
|
||||
import android.view.SurfaceView;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.webkit.WebChromeClient;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
/**
|
||||
* This class serves as a WebChromeClient to be set to a WebView, allowing it to play video.
|
||||
* Video will play differently depending on target API level (in-line, fullscreen, or both).
|
||||
*
|
||||
* It has been tested with the following video classes:
|
||||
* - android.widget.VideoView (typically API level <11)
|
||||
* - android.webkit.HTML5VideoFullScreen$VideoSurfaceView/VideoTextureView (typically API level 11-18)
|
||||
* - com.android.org.chromium.content.browser.ContentVideoView$VideoSurfaceView (typically API level 19+)
|
||||
*
|
||||
* Important notes:
|
||||
* - For API level 11+, android:hardwareAccelerated="true" must be set in the application manifest.
|
||||
* - The invoking activity must call VideoEnabledWebChromeClient's onBackPressed() inside of its own onBackPressed().
|
||||
* - Tested in Android API levels 8-19. Only tested on http://m.youtube.com.
|
||||
*
|
||||
* @author Cristian Perez (http://cpr.name)
|
||||
*
|
||||
*/
|
||||
public class VideoEnabledWebChromeClient extends WebChromeClient implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener
|
||||
{
|
||||
public interface ToggledFullscreenCallback
|
||||
{
|
||||
public void toggledFullscreen(boolean fullscreen);
|
||||
}
|
||||
|
||||
private View activityNonVideoView;
|
||||
private ViewGroup activityVideoView;
|
||||
private View loadingView;
|
||||
private VideoEnabledWebView webView;
|
||||
|
||||
private boolean isVideoFullscreen; // Indicates if the video is being displayed using a custom view (typically full-screen)
|
||||
private FrameLayout videoViewContainer;
|
||||
private CustomViewCallback videoViewCallback;
|
||||
|
||||
private ToggledFullscreenCallback toggledFullscreenCallback;
|
||||
|
||||
/**
|
||||
* Never use this constructor alone.
|
||||
* This constructor allows this class to be defined as an inline inner class in which the user can override methods
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public VideoEnabledWebChromeClient()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a video enabled WebChromeClient.
|
||||
* @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen.
|
||||
* @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView)
|
||||
{
|
||||
this.activityNonVideoView = activityNonVideoView;
|
||||
this.activityVideoView = activityVideoView;
|
||||
this.loadingView = null;
|
||||
this.webView = null;
|
||||
this.isVideoFullscreen = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a video enabled WebChromeClient.
|
||||
* @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen.
|
||||
* @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout.
|
||||
* @param loadingView A View to be shown while the video is loading (typically only used in API level <11). Must be already inflated and not attached to a parent view.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, View loadingView)
|
||||
{
|
||||
this.activityNonVideoView = activityNonVideoView;
|
||||
this.activityVideoView = activityVideoView;
|
||||
this.loadingView = loadingView;
|
||||
this.webView = null;
|
||||
this.isVideoFullscreen = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a video enabled WebChromeClient.
|
||||
* @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen.
|
||||
* @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout.
|
||||
* @param loadingView A View to be shown while the video is loading (typically only used in API level <11). Must be already inflated and not attached to a parent view.
|
||||
* @param webView The owner VideoEnabledWebView. Passing it will enable the VideoEnabledWebChromeClient to detect the HTML5 video ended event and exit full-screen.
|
||||
* Note: The web page must only contain one video tag in order for the HTML5 video ended event to work. This could be improved if needed (see Javascript code).
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, View loadingView, VideoEnabledWebView webView)
|
||||
{
|
||||
this.activityNonVideoView = activityNonVideoView;
|
||||
this.activityVideoView = activityVideoView;
|
||||
this.loadingView = loadingView;
|
||||
this.webView = webView;
|
||||
this.isVideoFullscreen = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the video is being displayed using a custom view (typically full-screen)
|
||||
* @return true it the video is being displayed using a custom view (typically full-screen)
|
||||
*/
|
||||
public boolean isVideoFullscreen()
|
||||
{
|
||||
return isVideoFullscreen;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a callback that will be fired when the video starts or finishes displaying using a custom view (typically full-screen)
|
||||
* @param callback A VideoEnabledWebChromeClient.ToggledFullscreenCallback callback
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public void setOnToggledFullscreen(ToggledFullscreenCallback callback)
|
||||
{
|
||||
this.toggledFullscreenCallback = callback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onShowCustomView(View view, CustomViewCallback callback)
|
||||
{
|
||||
if (view instanceof FrameLayout)
|
||||
{
|
||||
// A video wants to be shown
|
||||
FrameLayout frameLayout = (FrameLayout) view;
|
||||
View focusedChild = frameLayout.getFocusedChild();
|
||||
|
||||
// Save video related variables
|
||||
this.isVideoFullscreen = true;
|
||||
this.videoViewContainer = frameLayout;
|
||||
this.videoViewCallback = callback;
|
||||
|
||||
// Hide the non-video view, add the video view, and show it
|
||||
if (activityNonVideoView != null)
|
||||
{
|
||||
activityNonVideoView.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
|
||||
if (activityVideoView != null)
|
||||
{
|
||||
activityVideoView.addView(videoViewContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
|
||||
activityVideoView.setVisibility(View.VISIBLE);
|
||||
}
|
||||
|
||||
if (focusedChild instanceof android.widget.VideoView)
|
||||
{
|
||||
// android.widget.VideoView (typically API level <11)
|
||||
android.widget.VideoView videoView = (android.widget.VideoView) focusedChild;
|
||||
|
||||
// Handle all the required events
|
||||
videoView.setOnPreparedListener(this);
|
||||
videoView.setOnCompletionListener(this);
|
||||
videoView.setOnErrorListener(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Other classes, including:
|
||||
// - android.webkit.HTML5VideoFullScreen$VideoSurfaceView, which inherits from android.view.SurfaceView (typically API level 11-18)
|
||||
// - android.webkit.HTML5VideoFullScreen$VideoTextureView, which inherits from android.view.TextureView (typically API level 11-18)
|
||||
// - com.android.org.chromium.content.browser.ContentVideoView$VideoSurfaceView, which inherits from android.view.SurfaceView (typically API level 19+)
|
||||
|
||||
// Handle HTML5 video ended event only if the class is a SurfaceView
|
||||
// Test case: TextureView of Sony Xperia T API level 16 doesn't work fullscreen when loading the javascript below
|
||||
if (webView != null && webView.getSettings().getJavaScriptEnabled() && focusedChild instanceof SurfaceView)
|
||||
{
|
||||
// Run javascript code that detects the video end and notifies the Javascript interface
|
||||
String js = "javascript:";
|
||||
js += "var _ytrp_html5_video_last;";
|
||||
js += "var _ytrp_html5_video = document.getElementsByTagName('video')[0];";
|
||||
js += "if (_ytrp_html5_video != undefined && _ytrp_html5_video != _ytrp_html5_video_last) {";
|
||||
{
|
||||
js += "_ytrp_html5_video_last = _ytrp_html5_video;";
|
||||
js += "function _ytrp_html5_video_ended() {";
|
||||
{
|
||||
js += "_VideoEnabledWebView.notifyVideoEnd();"; // Must match Javascript interface name and method of VideoEnableWebView
|
||||
}
|
||||
js += "}";
|
||||
js += "_ytrp_html5_video.addEventListener('ended', _ytrp_html5_video_ended);";
|
||||
}
|
||||
js += "}";
|
||||
webView.loadUrl(js);
|
||||
}
|
||||
}
|
||||
|
||||
// Notify full-screen change
|
||||
if (toggledFullscreenCallback != null)
|
||||
{
|
||||
toggledFullscreenCallback.toggledFullscreen(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override @SuppressWarnings("deprecation")
|
||||
public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) // Available in API level 14+, deprecated in API level 18+
|
||||
{
|
||||
onShowCustomView(view, callback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onHideCustomView()
|
||||
{
|
||||
// This method should be manually called on video end in all cases because it's not always called automatically.
|
||||
// This method must be manually called on back key press (from this class' onBackPressed() method).
|
||||
|
||||
if (isVideoFullscreen)
|
||||
{
|
||||
// Hide the video view, remove it, and show the non-video view
|
||||
if (activityVideoView != null)
|
||||
{
|
||||
activityVideoView.setVisibility(View.INVISIBLE);
|
||||
activityVideoView.removeView(videoViewContainer);
|
||||
}
|
||||
|
||||
if (activityNonVideoView != null) {
|
||||
activityNonVideoView.setVisibility(View.VISIBLE);
|
||||
}
|
||||
|
||||
// Call back (only in API level <19, because in API level 19+ with chromium webview it crashes)
|
||||
if (videoViewCallback != null && !videoViewCallback.getClass().getName().contains(".chromium."))
|
||||
{
|
||||
videoViewCallback.onCustomViewHidden();
|
||||
}
|
||||
|
||||
// Reset video related variables
|
||||
isVideoFullscreen = false;
|
||||
videoViewContainer = null;
|
||||
videoViewCallback = null;
|
||||
|
||||
// Notify full-screen change
|
||||
if (toggledFullscreenCallback != null)
|
||||
{
|
||||
toggledFullscreenCallback.toggledFullscreen(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getVideoLoadingProgressView() // Video will start loading
|
||||
{
|
||||
if (loadingView != null)
|
||||
{
|
||||
loadingView.setVisibility(View.VISIBLE);
|
||||
return loadingView;
|
||||
}
|
||||
else
|
||||
{
|
||||
return super.getVideoLoadingProgressView();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPrepared(MediaPlayer mp) // Video will start playing, only called in the case of android.widget.VideoView (typically API level <11)
|
||||
{
|
||||
if (loadingView != null)
|
||||
{
|
||||
loadingView.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCompletion(MediaPlayer mp) // Video finished playing, only called in the case of android.widget.VideoView (typically API level <11)
|
||||
{
|
||||
onHideCustomView();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onError(MediaPlayer mp, int what, int extra) // Error while playing video, only called in the case of android.widget.VideoView (typically API level <11)
|
||||
{
|
||||
return false; // By returning false, onCompletion() will be called
|
||||
}
|
||||
|
||||
/**
|
||||
* Notifies the class that the back key has been pressed by the user.
|
||||
* This must be called from the Activity's onBackPressed(), and if it returns false, the activity itself should handle it. Otherwise don't do anything.
|
||||
* @return Returns true if the event was handled, and false if was not (video view is not visible)
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public boolean onBackPressed()
|
||||
{
|
||||
if (isVideoFullscreen)
|
||||
{
|
||||
onHideCustomView();
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
139
src/android/VideoEnabledWebView.java
Normal file
@@ -0,0 +1,139 @@
|
||||
package com.initialxy.cordova.themeablebrowser;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.AttributeSet;
|
||||
import android.util.Log;
|
||||
import android.webkit.WebChromeClient;
|
||||
import android.webkit.WebView;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* This class serves as a WebView to be used in conjunction with a VideoEnabledWebChromeClient.
|
||||
* It makes possible:
|
||||
* - To detect the HTML5 video ended event so that the VideoEnabledWebChromeClient can exit full-screen.
|
||||
*
|
||||
* Important notes:
|
||||
* - Javascript is enabled by default and must not be disabled with getSettings().setJavaScriptEnabled(false).
|
||||
* - setWebChromeClient() must be called before any loadData(), loadDataWithBaseURL() or loadUrl() method.
|
||||
*
|
||||
* @author Cristian Perez (http://cpr.name)
|
||||
*
|
||||
*/
|
||||
public class VideoEnabledWebView extends WebView
|
||||
{
|
||||
public class JavascriptInterface
|
||||
{
|
||||
@android.webkit.JavascriptInterface @SuppressWarnings("unused")
|
||||
public void notifyVideoEnd() // Must match Javascript interface method of VideoEnabledWebChromeClient
|
||||
{
|
||||
Log.d("___", "GOT IT");
|
||||
// This code is not executed in the UI thread, so we must force that to happen
|
||||
new Handler(Looper.getMainLooper()).post(new Runnable()
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
if (videoEnabledWebChromeClient != null)
|
||||
{
|
||||
videoEnabledWebChromeClient.onHideCustomView();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private VideoEnabledWebChromeClient videoEnabledWebChromeClient;
|
||||
private boolean addedJavascriptInterface;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public VideoEnabledWebView(Context context)
|
||||
{
|
||||
super(context);
|
||||
addedJavascriptInterface = false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public VideoEnabledWebView(Context context, AttributeSet attrs)
|
||||
{
|
||||
super(context, attrs);
|
||||
addedJavascriptInterface = false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public VideoEnabledWebView(Context context, AttributeSet attrs, int defStyle)
|
||||
{
|
||||
super(context, attrs, defStyle);
|
||||
addedJavascriptInterface = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the video is being displayed using a custom view (typically full-screen)
|
||||
* @return true it the video is being displayed using a custom view (typically full-screen)
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public boolean isVideoFullscreen()
|
||||
{
|
||||
return videoEnabledWebChromeClient != null && videoEnabledWebChromeClient.isVideoFullscreen();
|
||||
}
|
||||
|
||||
/**
|
||||
* Pass only a VideoEnabledWebChromeClient instance.
|
||||
*/
|
||||
@Override @SuppressLint("SetJavaScriptEnabled")
|
||||
public void setWebChromeClient(WebChromeClient client)
|
||||
{
|
||||
getSettings().setJavaScriptEnabled(true);
|
||||
|
||||
if (client instanceof VideoEnabledWebChromeClient)
|
||||
{
|
||||
this.videoEnabledWebChromeClient = (VideoEnabledWebChromeClient) client;
|
||||
}
|
||||
|
||||
super.setWebChromeClient(client);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadData(String data, String mimeType, String encoding)
|
||||
{
|
||||
addJavascriptInterface();
|
||||
super.loadData(data, mimeType, encoding);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)
|
||||
{
|
||||
addJavascriptInterface();
|
||||
super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadUrl(String url)
|
||||
{
|
||||
addJavascriptInterface();
|
||||
super.loadUrl(url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadUrl(String url, Map<String, String> additionalHttpHeaders)
|
||||
{
|
||||
addJavascriptInterface();
|
||||
super.loadUrl(url, additionalHttpHeaders);
|
||||
}
|
||||
|
||||
private void addJavascriptInterface()
|
||||
{
|
||||
if (!addedJavascriptInterface)
|
||||
{
|
||||
// Add javascript interface to be called when the video ends (must be done before page load)
|
||||
//noinspection all
|
||||
addJavascriptInterface(new JavascriptInterface(), "_VideoEnabledWebView"); // Must match Javascript interface name of VideoEnabledWebChromeClient
|
||||
|
||||
addedJavascriptInterface = true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
BIN
src/android/res/drawable-xhdpi/back.png
Normal file
|
After Width: | Height: | Size: 447 B |
BIN
src/android/res/drawable-xhdpi/back_pressed.png
Normal file
|
After Width: | Height: | Size: 370 B |
BIN
src/android/res/drawable-xhdpi/close.png
Normal file
|
After Width: | Height: | Size: 563 B |
BIN
src/android/res/drawable-xhdpi/close_pressed.png
Normal file
|
After Width: | Height: | Size: 452 B |
BIN
src/android/res/drawable-xhdpi/forward.png
Normal file
|
After Width: | Height: | Size: 441 B |
BIN
src/android/res/drawable-xhdpi/forward_pressed.png
Normal file
|
After Width: | Height: | Size: 369 B |
BIN
src/android/res/drawable-xhdpi/menu.png
Normal file
|
After Width: | Height: | Size: 527 B |
BIN
src/android/res/drawable-xhdpi/menu_pressed.png
Normal file
|
After Width: | Height: | Size: 612 B |
BIN
src/android/res/drawable-xhdpi/share.png
Normal file
|
After Width: | Height: | Size: 1.2 KiB |
BIN
src/android/res/drawable-xhdpi/share_pressed.png
Normal file
|
After Width: | Height: | Size: 926 B |
43
src/blackberry10/README.md
Normal file
@@ -0,0 +1,43 @@
|
||||
<!---
|
||||
license: Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
-->
|
||||
# BlackBerry 10 In-App-Browser Plugin
|
||||
|
||||
The in app browser functionality is entirely contained within common js. There is no native implementation required.
|
||||
To install this plugin, follow the [Command-line Interface Guide](http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface).
|
||||
|
||||
If you are not using the Cordova Command-line Interface, follow [Using Plugman to Manage Plugins](http://cordova.apache.org/docs/en/edge/guide_plugin_ref_plugman.md.html).
|
||||
./cordova-plugin-battery-status/README.md
|
||||
./cordova-plugin-camera/README.md
|
||||
./cordova-plugin-console/README.md
|
||||
./cordova-plugin-contacts/README.md
|
||||
./cordova-plugin-device/README.md
|
||||
./cordova-plugin-device-motion/README.md
|
||||
./cordova-plugin-device-orientation/README.md
|
||||
./cordova-plugin-device-orientation/src/blackberry10/README.md
|
||||
./cordova-plugin-file/README.md
|
||||
./cordova-plugin-file-transfer/README.md
|
||||
./cordova-plugin-geolocation/README.md
|
||||
./cordova-plugin-globalization/README.md
|
||||
./cordova-plugin-inappbrowser/README.md
|
||||
./cordova-plugin-inappbrowser/src/blackberry10/README.md
|
||||
./cordova-plugin-media/README.md
|
||||
./cordova-plugin-media-capture/README.md
|
||||
./cordova-plugin-network-information/README.md
|
||||
./cordova-plugin-splashscreen/README.md
|
||||
./cordova-plugin-vibration/README.md
|
||||
221
src/browser/InAppBrowserProxy.js
Normal file
@@ -0,0 +1,221 @@
|
||||
/*
|
||||
*
|
||||
* 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'),
|
||||
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 === "_system" || target === "_self" || !target) {
|
||||
window.location = strUrl;
|
||||
} 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);
|
||||
191
src/firefoxos/InAppBrowserProxy.js
Normal 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);
|
||||
130
src/ios/CDVThemeableBrowser.h
Normal file
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
*/
|
||||
|
||||
#import <Cordova/CDVPlugin.h>
|
||||
#import <Cordova/CDVInvokedUrlCommand.h>
|
||||
#import <Cordova/CDVScreenOrientationDelegate.h>
|
||||
#import "CDVWKWebViewUIDelegate.h"
|
||||
|
||||
@interface CDVThemeableBrowserOptions : NSObject {}
|
||||
|
||||
@property (nonatomic) BOOL location;
|
||||
@property (nonatomic) NSString* closebuttoncaption;
|
||||
@property (nonatomic) NSString* toolbarposition;
|
||||
@property (nonatomic) BOOL clearcache;
|
||||
@property (nonatomic) BOOL clearsessioncache;
|
||||
|
||||
@property (nonatomic) NSString* presentationstyle;
|
||||
@property (nonatomic) NSString* transitionstyle;
|
||||
|
||||
@property (nonatomic) BOOL zoom;
|
||||
@property (nonatomic) BOOL mediaplaybackrequiresuseraction;
|
||||
@property (nonatomic) BOOL allowinlinemediaplayback;
|
||||
@property (nonatomic) BOOL keyboarddisplayrequiresuseraction;
|
||||
@property (nonatomic) BOOL suppressesincrementalrendering;
|
||||
@property (nonatomic) BOOL hidden;
|
||||
@property (nonatomic) BOOL disallowoverscroll;
|
||||
|
||||
@property (nonatomic) NSDictionary* statusbar;
|
||||
@property (nonatomic) NSDictionary* toolbar;
|
||||
@property (nonatomic) NSDictionary* title;
|
||||
@property (nonatomic) NSDictionary* backButton;
|
||||
@property (nonatomic) NSDictionary* forwardButton;
|
||||
@property (nonatomic) NSDictionary* closeButton;
|
||||
@property (nonatomic) NSDictionary* menu;
|
||||
@property (nonatomic) NSArray* customButtons;
|
||||
@property (nonatomic) BOOL backButtonCanClose;
|
||||
@property (nonatomic) BOOL disableAnimation;
|
||||
@property (nonatomic) BOOL fullscreen;
|
||||
|
||||
@property (nonatomic) BOOL enableviewportscale;
|
||||
|
||||
@end
|
||||
|
||||
@class CDVThemeableBrowserViewController;
|
||||
|
||||
@interface CDVThemeableBrowser : CDVPlugin {
|
||||
BOOL _injectedIframeBridge;
|
||||
}
|
||||
|
||||
@property (nonatomic, retain) CDVThemeableBrowserViewController* themeableBrowserViewController;
|
||||
@property (nonatomic, copy) NSString* callbackId;
|
||||
@property (nonatomic, copy) NSRegularExpression *callbackIdPattern;
|
||||
|
||||
- (CDVThemeableBrowserOptions*)parseOptions:(NSString*)options;
|
||||
- (void)open:(CDVInvokedUrlCommand*)command;
|
||||
- (void)close:(CDVInvokedUrlCommand*)command;
|
||||
- (void)injectScriptCode:(CDVInvokedUrlCommand*)command;
|
||||
- (void)show:(CDVInvokedUrlCommand*)command;
|
||||
- (void)show:(CDVInvokedUrlCommand*)command withAnimation:(BOOL)animated;
|
||||
- (void)reload:(CDVInvokedUrlCommand*)command;
|
||||
|
||||
@end
|
||||
|
||||
@interface CDVThemeableBrowserViewController : UIViewController <UIWebViewDelegate, CDVScreenOrientationDelegate, UIActionSheetDelegate>{
|
||||
@private
|
||||
NSString* _userAgent;
|
||||
NSString* _prevUserAgent;
|
||||
NSInteger _userAgentLockToken;
|
||||
UIStatusBarStyle _statusBarStyle;
|
||||
CDVThemeableBrowserOptions *_browserOptions;
|
||||
|
||||
CDVWKWebViewUIDelegate* _webViewDelegate;
|
||||
|
||||
}
|
||||
|
||||
@property (nonatomic, strong) IBOutlet WKWebView* webView;
|
||||
@property (nonatomic, strong) IBOutlet UIButton* closeButton;
|
||||
@property (nonatomic, strong) IBOutlet UILabel* addressLabel;
|
||||
@property (nonatomic, strong) IBOutlet UILabel* titleLabel;
|
||||
@property (nonatomic, strong) IBOutlet UIButton* backButton;
|
||||
@property (nonatomic, strong) IBOutlet UIButton* forwardButton;
|
||||
@property (nonatomic, strong) IBOutlet UIButton* menuButton;
|
||||
@property (nonatomic, strong) IBOutlet UIActivityIndicatorView* spinner;
|
||||
@property (nonatomic, strong) IBOutlet UIView* toolbar;
|
||||
|
||||
@property (nonatomic, strong) NSArray* leftButtons;
|
||||
@property (nonatomic, strong) NSArray* rightButtons;
|
||||
|
||||
@property (nonatomic, weak) id <CDVScreenOrientationDelegate> orientationDelegate;
|
||||
@property (nonatomic, weak) CDVThemeableBrowser* navigationDelegate;
|
||||
@property (nonatomic) NSURL* currentURL;
|
||||
@property (nonatomic) CGFloat titleOffset;
|
||||
|
||||
@property (nonatomic) WKWebViewConfiguration* configuration;
|
||||
|
||||
- (void)close;
|
||||
- (void)reload;
|
||||
- (void)navigateTo:(NSURL*)url;
|
||||
- (void)showLocationBar:(BOOL)show;
|
||||
- (void)showToolBar:(BOOL)show : (NSString*) toolbarPosition;
|
||||
- (void)setCloseButtonTitle:(NSString*)title;
|
||||
|
||||
- (id)initWithBrowserOptions:(CDVThemeableBrowserOptions*) browserOptions navigationDelegate:(CDVThemeableBrowser*) navigationDelegate statusBarStyle:(UIStatusBarStyle) statusBarStyle;
|
||||
|
||||
+ (UIColor *)colorFromRGBA:(NSString *)rgba;
|
||||
|
||||
@end
|
||||
|
||||
@interface CDVThemeableBrowserNavigationController : UINavigationController
|
||||
|
||||
@property (nonatomic, weak) id <CDVScreenOrientationDelegate> orientationDelegate;
|
||||
|
||||
@end
|
||||
|
||||
1779
src/ios/CDVThemeableBrowser.m
Normal file
32
src/ios/CDVWKThemeableBrowserUIDelegate.h
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
*/
|
||||
|
||||
#import <WebKit/WebKit.h>
|
||||
|
||||
@interface CDVWKThemeableBrowserUIDelegate : NSObject <WKUIDelegate>{
|
||||
@private
|
||||
UIViewController* _viewController;
|
||||
}
|
||||
|
||||
@property (nonatomic, copy) NSString* title;
|
||||
|
||||
- (instancetype)initWithTitle:(NSString*)title;
|
||||
-(void) setViewController:(UIViewController*) viewController;
|
||||
|
||||
@end
|
||||
127
src/ios/CDVWKThemeableBrowserUIDelegate.m
Normal file
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
*/
|
||||
|
||||
#import "CDVWKThemeableBrowserUIDelegate.h"
|
||||
|
||||
@implementation CDVWKThemeableBrowserUIDelegate
|
||||
|
||||
- (instancetype)initWithTitle:(NSString*)title
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
self.title = title;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void) webView:(WKWebView*)webView runJavaScriptAlertPanelWithMessage:(NSString*)message
|
||||
initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void (^)(void))completionHandler
|
||||
{
|
||||
UIAlertController* alert = [UIAlertController alertControllerWithTitle:self.title
|
||||
message:message
|
||||
preferredStyle:UIAlertControllerStyleAlert];
|
||||
|
||||
UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK")
|
||||
style:UIAlertActionStyleDefault
|
||||
handler:^(UIAlertAction* action)
|
||||
{
|
||||
completionHandler();
|
||||
[alert dismissViewControllerAnimated:YES completion:nil];
|
||||
}];
|
||||
|
||||
[alert addAction:ok];
|
||||
|
||||
[[self getViewController] presentViewController:alert animated:YES completion:nil];
|
||||
}
|
||||
|
||||
- (void) webView:(WKWebView*)webView runJavaScriptConfirmPanelWithMessage:(NSString*)message
|
||||
initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void (^)(BOOL result))completionHandler
|
||||
{
|
||||
UIAlertController* alert = [UIAlertController alertControllerWithTitle:self.title
|
||||
message:message
|
||||
preferredStyle:UIAlertControllerStyleAlert];
|
||||
|
||||
UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK")
|
||||
style:UIAlertActionStyleDefault
|
||||
handler:^(UIAlertAction* action)
|
||||
{
|
||||
completionHandler(YES);
|
||||
[alert dismissViewControllerAnimated:YES completion:nil];
|
||||
}];
|
||||
|
||||
[alert addAction:ok];
|
||||
|
||||
UIAlertAction* cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel")
|
||||
style:UIAlertActionStyleDefault
|
||||
handler:^(UIAlertAction* action)
|
||||
{
|
||||
completionHandler(NO);
|
||||
[alert dismissViewControllerAnimated:YES completion:nil];
|
||||
}];
|
||||
[alert addAction:cancel];
|
||||
|
||||
[[self getViewController] presentViewController:alert animated:YES completion:nil];
|
||||
}
|
||||
|
||||
- (void) webView:(WKWebView*)webView runJavaScriptTextInputPanelWithPrompt:(NSString*)prompt
|
||||
defaultText:(NSString*)defaultText initiatedByFrame:(WKFrameInfo*)frame
|
||||
completionHandler:(void (^)(NSString* result))completionHandler
|
||||
{
|
||||
UIAlertController* alert = [UIAlertController alertControllerWithTitle:self.title
|
||||
message:prompt
|
||||
preferredStyle:UIAlertControllerStyleAlert];
|
||||
|
||||
UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK")
|
||||
style:UIAlertActionStyleDefault
|
||||
handler:^(UIAlertAction* action)
|
||||
{
|
||||
completionHandler(((UITextField*)alert.textFields[0]).text);
|
||||
[alert dismissViewControllerAnimated:YES completion:nil];
|
||||
}];
|
||||
|
||||
[alert addAction:ok];
|
||||
|
||||
UIAlertAction* cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel")
|
||||
style:UIAlertActionStyleDefault
|
||||
handler:^(UIAlertAction* action)
|
||||
{
|
||||
completionHandler(nil);
|
||||
[alert dismissViewControllerAnimated:YES completion:nil];
|
||||
}];
|
||||
[alert addAction:cancel];
|
||||
|
||||
[alert addTextFieldWithConfigurationHandler:^(UITextField* textField) {
|
||||
textField.text = defaultText;
|
||||
}];
|
||||
|
||||
[[self getViewController] presentViewController:alert animated:YES completion:nil];
|
||||
}
|
||||
|
||||
-(UIViewController*) getViewController
|
||||
{
|
||||
return _viewController;
|
||||
}
|
||||
|
||||
-(void) setViewController:(UIViewController*) viewController
|
||||
{
|
||||
_viewController = viewController;
|
||||
}
|
||||
|
||||
@end
|
||||
1
src/ios/Resources/README.md
Normal file
@@ -0,0 +1 @@
|
||||
Files here are for sample during dev purposes only. They are not actually imported to user's project as part of this plugin.
|
||||
BIN
src/ios/Resources/back@2x.png
Normal file
|
After Width: | Height: | Size: 447 B |
BIN
src/ios/Resources/back_pressed@2x.png
Normal file
|
After Width: | Height: | Size: 370 B |
BIN
src/ios/Resources/close@2x.png
Normal file
|
After Width: | Height: | Size: 563 B |
BIN
src/ios/Resources/close_pressed@2x.png
Normal file
|
After Width: | Height: | Size: 452 B |
BIN
src/ios/Resources/forward@2x.png
Normal file
|
After Width: | Height: | Size: 441 B |
BIN
src/ios/Resources/forward_pressed@2x.png
Normal file
|
After Width: | Height: | Size: 369 B |
BIN
src/ios/Resources/menu@2x.png
Normal file
|
After Width: | Height: | Size: 527 B |
BIN
src/ios/Resources/menu_pressed@2x.png
Normal file
|
After Width: | Height: | Size: 612 B |
BIN
src/ios/Resources/share@2x.png
Normal file
|
After Width: | Height: | Size: 1.2 KiB |
BIN
src/ios/Resources/share_pressed@2x.png
Normal file
|
After Width: | Height: | Size: 926 B |
92
src/ubuntu/InAppBrowser.qml
Normal 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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
29
src/ubuntu/InAppBrowser_escapeScript.js
Normal 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
|
After Width: | Height: | Size: 461 B |
105
src/ubuntu/inappbrowser.cpp
Normal 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
@@ -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
|
||||
326
src/windows/InAppBrowserProxy.js
Normal file
@@ -0,0 +1,326 @@
|
||||
/*
|
||||
*
|
||||
* 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'),
|
||||
channel = require('cordova/channel'),
|
||||
urlutil = require('cordova/urlutil');
|
||||
|
||||
var browserWrap,
|
||||
popup,
|
||||
navigationButtonsDiv,
|
||||
navigationButtonsDivInner,
|
||||
backButton,
|
||||
forwardButton,
|
||||
closeButton,
|
||||
bodyOverflowStyle;
|
||||
|
||||
// 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) {
|
||||
callback({ type: e.isSuccess ? "loadstop" : "loaderror", url: e.uri}, {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}, {keepCallback: true});
|
||||
});
|
||||
|
||||
element.addEventListener("MSWebViewContentLoading", function (e) {
|
||||
if (navigationButtonsDiv) {
|
||||
backButton.disabled = !popup.canGoBack;
|
||||
forwardButton.disabled = !popup.canGoForward;
|
||||
}
|
||||
});
|
||||
} 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) {
|
||||
if (browserWrap) {
|
||||
if (win) win({ 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) {
|
||||
if (browserWrap) {
|
||||
browserWrap.style.display = "block";
|
||||
}
|
||||
},
|
||||
open: function (win, lose, args) {
|
||||
var strUrl = args[0],
|
||||
target = args[1],
|
||||
features = args[2],
|
||||
url;
|
||||
|
||||
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(win);
|
||||
}, 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% - 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.innerText = "<-";
|
||||
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.innerText = "->";
|
||||
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.innerText = "x";
|
||||
closeButton.addEventListener("click", function (e) {
|
||||
setTimeout(function () {
|
||||
IAB.close(win);
|
||||
}, 0);
|
||||
});
|
||||
|
||||
if (!isWebViewAvailable) {
|
||||
// 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);
|
||||
|
||||
if (isWebViewAvailable) {
|
||||
strUrl = strUrl.replace("ms-appx://", "ms-appx-web://");
|
||||
}
|
||||
popup.src = strUrl;
|
||||
}
|
||||
},
|
||||
|
||||
injectScriptCode: function (win, fail, args) {
|
||||
var code = args[0],
|
||||
hasCallback = args[1];
|
||||
|
||||
if (isWebViewAvailable && browserWrap && popup) {
|
||||
var op = popup.invokeScriptAsync("eval", code);
|
||||
op.oncomplete = function (e) {
|
||||
var result = [e.target.result];
|
||||
hasCallback && win(result);
|
||||
};
|
||||
op.onerror = function () { };
|
||||
op.start();
|
||||
}
|
||||
},
|
||||
|
||||
injectScriptFile: function (win, fail, args) {
|
||||
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) {
|
||||
var code = args[0],
|
||||
hasCallback = args[1];
|
||||
|
||||
if (isWebViewAvailable && browserWrap && popup) {
|
||||
injectCSS(popup, code, hasCallback && win);
|
||||
}
|
||||
},
|
||||
|
||||
injectStyleFile: function (win, fail, args) {
|
||||
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);
|
||||
515
src/wp/InAppBrowser.cs
Normal file
@@ -0,0 +1,515 @@
|
||||
/*
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Media;
|
||||
using Microsoft.Phone.Controls;
|
||||
using Microsoft.Phone.Shell;
|
||||
|
||||
#if WP8
|
||||
using System.Threading.Tasks;
|
||||
using Windows.ApplicationModel;
|
||||
using Windows.Storage;
|
||||
using Windows.System;
|
||||
|
||||
//Use alias in case Cordova File Plugin is enabled. Then the File class will be declared in both and error will occur.
|
||||
using IOFile = System.IO.File;
|
||||
#else
|
||||
using Microsoft.Phone.Tasks;
|
||||
#endif
|
||||
|
||||
namespace WPCordovaClassLib.Cordova.Commands
|
||||
{
|
||||
[DataContract]
|
||||
public class BrowserOptions
|
||||
{
|
||||
[DataMember]
|
||||
public string url;
|
||||
|
||||
[DataMember]
|
||||
public bool isGeolocationEnabled;
|
||||
}
|
||||
|
||||
public class InAppBrowser : BaseCommand
|
||||
{
|
||||
|
||||
private static WebBrowser browser;
|
||||
private static ApplicationBarIconButton backButton;
|
||||
private static ApplicationBarIconButton fwdButton;
|
||||
|
||||
protected ApplicationBar AppBar;
|
||||
|
||||
protected bool ShowLocation {get;set;}
|
||||
protected bool StartHidden {get;set;}
|
||||
|
||||
protected string NavigationCallbackId { get; set; }
|
||||
|
||||
public void open(string options)
|
||||
{
|
||||
// reset defaults on ShowLocation + StartHidden features
|
||||
ShowLocation = true;
|
||||
StartHidden = false;
|
||||
|
||||
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
//BrowserOptions opts = JSON.JsonHelper.Deserialize<BrowserOptions>(options);
|
||||
string urlLoc = args[0];
|
||||
string target = args[1];
|
||||
string featString = args[2];
|
||||
this.NavigationCallbackId = args[3];
|
||||
|
||||
if (!string.IsNullOrEmpty(featString))
|
||||
{
|
||||
string[] features = featString.Split(',');
|
||||
foreach (string str in features)
|
||||
{
|
||||
try
|
||||
{
|
||||
string[] split = str.Split('=');
|
||||
switch (split[0])
|
||||
{
|
||||
case "location":
|
||||
ShowLocation = split[1].StartsWith("yes", StringComparison.OrdinalIgnoreCase);
|
||||
break;
|
||||
case "hidden":
|
||||
StartHidden = split[1].StartsWith("yes", StringComparison.OrdinalIgnoreCase);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// some sort of invalid param was passed, moving on ...
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
_self - opens in the Cordova WebView if url is in the white-list, else it opens in the InAppBrowser
|
||||
_blank - always open in the InAppBrowser
|
||||
_system - always open in the system web browser
|
||||
*/
|
||||
switch (target)
|
||||
{
|
||||
case "_blank":
|
||||
ShowInAppBrowser(urlLoc);
|
||||
break;
|
||||
case "_self":
|
||||
ShowCordovaBrowser(urlLoc);
|
||||
break;
|
||||
case "_system":
|
||||
ShowSystemBrowser(urlLoc);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void show(string options)
|
||||
{
|
||||
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
|
||||
|
||||
if (browser != null)
|
||||
{
|
||||
Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
browser.Visibility = Visibility.Visible;
|
||||
AppBar.IsVisible = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void injectScriptCode(string options)
|
||||
{
|
||||
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
|
||||
bool bCallback = false;
|
||||
if (bool.TryParse(args[1], out bCallback)) { };
|
||||
|
||||
string callbackId = args[2];
|
||||
|
||||
if (browser != null)
|
||||
{
|
||||
Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
var res = browser.InvokeScript("eval", new string[] { args[0] });
|
||||
|
||||
if (bCallback)
|
||||
{
|
||||
PluginResult result = new PluginResult(PluginResult.Status.OK, res.ToString());
|
||||
result.KeepCallback = false;
|
||||
this.DispatchCommandResult(result);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void injectScriptFile(string options)
|
||||
{
|
||||
Debug.WriteLine("Error : Windows Phone cordova-plugin-inappbrowser does not currently support executeScript");
|
||||
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
// throw new NotImplementedException("Windows Phone does not currently support 'executeScript'");
|
||||
}
|
||||
|
||||
public void injectStyleCode(string options)
|
||||
{
|
||||
Debug.WriteLine("Error : Windows Phone cordova-plugin-inappbrowser does not currently support insertCSS");
|
||||
return;
|
||||
|
||||
//string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
//bool bCallback = false;
|
||||
//if (bool.TryParse(args[1], out bCallback)) { };
|
||||
|
||||
//string callbackId = args[2];
|
||||
|
||||
//if (browser != null)
|
||||
//{
|
||||
//Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
//{
|
||||
// if (bCallback)
|
||||
// {
|
||||
// string cssInsertString = "try{(function(doc){var c = '<style>body{background-color:#ffff00;}</style>'; doc.head.innerHTML += c;})(document);}catch(ex){alert('oops : ' + ex.message);}";
|
||||
// //cssInsertString = cssInsertString.Replace("_VALUE_", args[0]);
|
||||
// Debug.WriteLine("cssInsertString = " + cssInsertString);
|
||||
// var res = browser.InvokeScript("eval", new string[] { cssInsertString });
|
||||
// if (bCallback)
|
||||
// {
|
||||
// PluginResult result = new PluginResult(PluginResult.Status.OK, res.ToString());
|
||||
// result.KeepCallback = false;
|
||||
// this.DispatchCommandResult(result);
|
||||
// }
|
||||
// }
|
||||
|
||||
//});
|
||||
//}
|
||||
}
|
||||
|
||||
public void injectStyleFile(string options)
|
||||
{
|
||||
Debug.WriteLine("Error : Windows Phone cordova-plugin-inappbrowser does not currently support insertCSS");
|
||||
return;
|
||||
|
||||
//string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
|
||||
//throw new NotImplementedException("Windows Phone does not currently support 'insertCSS'");
|
||||
}
|
||||
|
||||
private void ShowCordovaBrowser(string url)
|
||||
{
|
||||
Uri loc = new Uri(url, UriKind.RelativeOrAbsolute);
|
||||
Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
|
||||
if (frame != null)
|
||||
{
|
||||
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
|
||||
if (page != null)
|
||||
{
|
||||
CordovaView cView = page.FindName("CordovaView") as CordovaView;
|
||||
if (cView != null)
|
||||
{
|
||||
WebBrowser br = cView.Browser;
|
||||
br.Navigate2(loc);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#if WP8
|
||||
private async void ShowSystemBrowser(string url)
|
||||
{
|
||||
var pathUri = new Uri(url, UriKind.Absolute);
|
||||
if (pathUri.Scheme == Uri.UriSchemeHttp || pathUri.Scheme == Uri.UriSchemeHttps)
|
||||
{
|
||||
await Launcher.LaunchUriAsync(pathUri);
|
||||
return;
|
||||
}
|
||||
|
||||
var file = await GetFile(pathUri.AbsolutePath.Replace('/', Path.DirectorySeparatorChar));
|
||||
if (file != null)
|
||||
{
|
||||
await Launcher.LaunchFileAsync(file);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.WriteLine("File not found.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<StorageFile> GetFile(string fileName)
|
||||
{
|
||||
//first try to get the file from the isolated storage
|
||||
var localFolder = ApplicationData.Current.LocalFolder;
|
||||
if (IOFile.Exists(Path.Combine(localFolder.Path, fileName)))
|
||||
{
|
||||
return await localFolder.GetFileAsync(fileName);
|
||||
}
|
||||
|
||||
//if file is not found try to get it from the xap
|
||||
var filePath = Path.Combine(Package.Current.InstalledLocation.Path, fileName);
|
||||
if (IOFile.Exists(filePath))
|
||||
{
|
||||
return await StorageFile.GetFileFromPathAsync(filePath);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
#else
|
||||
private void ShowSystemBrowser(string url)
|
||||
{
|
||||
WebBrowserTask webBrowserTask = new WebBrowserTask();
|
||||
webBrowserTask.Uri = new Uri(url, UriKind.Absolute);
|
||||
webBrowserTask.Show();
|
||||
}
|
||||
#endif
|
||||
|
||||
private void ShowInAppBrowser(string url)
|
||||
{
|
||||
Uri loc = new Uri(url, UriKind.RelativeOrAbsolute);
|
||||
|
||||
Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (browser != null)
|
||||
{
|
||||
//browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
|
||||
browser.Navigate2(loc);
|
||||
}
|
||||
else
|
||||
{
|
||||
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
|
||||
if (frame != null)
|
||||
{
|
||||
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
|
||||
|
||||
string baseImageUrl = "Images/";
|
||||
|
||||
if (page != null)
|
||||
{
|
||||
Grid grid = page.FindName("LayoutRoot") as Grid;
|
||||
if (grid != null)
|
||||
{
|
||||
browser = new WebBrowser();
|
||||
browser.IsScriptEnabled = true;
|
||||
browser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);
|
||||
|
||||
browser.Navigating += new EventHandler<NavigatingEventArgs>(browser_Navigating);
|
||||
browser.NavigationFailed += new System.Windows.Navigation.NavigationFailedEventHandler(browser_NavigationFailed);
|
||||
browser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(browser_Navigated);
|
||||
browser.Navigate2(loc);
|
||||
|
||||
if (StartHidden)
|
||||
{
|
||||
browser.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
|
||||
//browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
|
||||
grid.Children.Add(browser);
|
||||
}
|
||||
|
||||
ApplicationBar bar = new ApplicationBar();
|
||||
bar.BackgroundColor = Colors.Gray;
|
||||
bar.IsMenuEnabled = false;
|
||||
|
||||
backButton = new ApplicationBarIconButton();
|
||||
backButton.Text = "Back";
|
||||
|
||||
backButton.IconUri = new Uri(baseImageUrl + "appbar.back.rest.png", UriKind.Relative);
|
||||
backButton.Click += new EventHandler(backButton_Click);
|
||||
bar.Buttons.Add(backButton);
|
||||
|
||||
|
||||
fwdButton = new ApplicationBarIconButton();
|
||||
fwdButton.Text = "Forward";
|
||||
fwdButton.IconUri = new Uri(baseImageUrl + "appbar.next.rest.png", UriKind.Relative);
|
||||
fwdButton.Click += new EventHandler(fwdButton_Click);
|
||||
bar.Buttons.Add(fwdButton);
|
||||
|
||||
ApplicationBarIconButton closeBtn = new ApplicationBarIconButton();
|
||||
closeBtn.Text = "Close";
|
||||
closeBtn.IconUri = new Uri(baseImageUrl + "appbar.close.rest.png", UriKind.Relative);
|
||||
closeBtn.Click += new EventHandler(closeBtn_Click);
|
||||
bar.Buttons.Add(closeBtn);
|
||||
|
||||
page.ApplicationBar = bar;
|
||||
bar.IsVisible = !StartHidden;
|
||||
AppBar = bar;
|
||||
|
||||
page.BackKeyPress += page_BackKeyPress;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void page_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
|
||||
{
|
||||
#if WP8
|
||||
if (browser.CanGoBack)
|
||||
{
|
||||
browser.GoBack();
|
||||
}
|
||||
else
|
||||
{
|
||||
close();
|
||||
}
|
||||
e.Cancel = true;
|
||||
#else
|
||||
browser.InvokeScript("execScript", "history.back();");
|
||||
#endif
|
||||
}
|
||||
|
||||
void browser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void fwdButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (browser != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
#if WP8
|
||||
browser.GoForward();
|
||||
#else
|
||||
browser.InvokeScript("execScript", "history.forward();");
|
||||
#endif
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void backButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (browser != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
#if WP8
|
||||
browser.GoBack();
|
||||
#else
|
||||
browser.InvokeScript("execScript", "history.back();");
|
||||
#endif
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void closeBtn_Click(object sender, EventArgs e)
|
||||
{
|
||||
this.close();
|
||||
}
|
||||
|
||||
|
||||
public void close(string options = "")
|
||||
{
|
||||
if (browser != null)
|
||||
{
|
||||
Deployment.Current.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
|
||||
if (frame != null)
|
||||
{
|
||||
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
|
||||
if (page != null)
|
||||
{
|
||||
Grid grid = page.FindName("LayoutRoot") as Grid;
|
||||
if (grid != null)
|
||||
{
|
||||
grid.Children.Remove(browser);
|
||||
}
|
||||
page.ApplicationBar = null;
|
||||
page.BackKeyPress -= page_BackKeyPress;
|
||||
}
|
||||
}
|
||||
|
||||
browser = null;
|
||||
string message = "{\"type\":\"exit\"}";
|
||||
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
|
||||
result.KeepCallback = false;
|
||||
this.DispatchCommandResult(result, NavigationCallbackId);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
|
||||
{
|
||||
#if WP8
|
||||
if (browser != null)
|
||||
{
|
||||
backButton.IsEnabled = browser.CanGoBack;
|
||||
fwdButton.IsEnabled = browser.CanGoForward;
|
||||
|
||||
}
|
||||
#endif
|
||||
string message = "{\"type\":\"loadstop\", \"url\":\"" + e.Uri.OriginalString + "\"}";
|
||||
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
|
||||
result.KeepCallback = true;
|
||||
this.DispatchCommandResult(result, NavigationCallbackId);
|
||||
}
|
||||
|
||||
void browser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
|
||||
{
|
||||
string message = "{\"type\":\"error\",\"url\":\"" + e.Uri.OriginalString + "\"}";
|
||||
PluginResult result = new PluginResult(PluginResult.Status.ERROR, message);
|
||||
result.KeepCallback = true;
|
||||
this.DispatchCommandResult(result, NavigationCallbackId);
|
||||
}
|
||||
|
||||
void browser_Navigating(object sender, NavigatingEventArgs e)
|
||||
{
|
||||
string message = "{\"type\":\"loadstart\",\"url\":\"" + e.Uri.OriginalString + "\"}";
|
||||
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
|
||||
result.KeepCallback = true;
|
||||
this.DispatchCommandResult(result, NavigationCallbackId);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal static class WebBrowserExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Improved method to initiate request to the provided URI. Supports 'data:text/html' urls.
|
||||
/// </summary>
|
||||
/// <param name="browser">The browser instance</param>
|
||||
/// <param name="uri">The requested uri</param>
|
||||
internal static void Navigate2(this WebBrowser browser, Uri uri)
|
||||
{
|
||||
// IE10 does not support data uri so we use NavigateToString method instead
|
||||
if (uri.Scheme == "data")
|
||||
{
|
||||
// we should remove the scheme identifier and unescape the uri
|
||||
string uriString = Uri.UnescapeDataString(uri.AbsoluteUri);
|
||||
// format is 'data:text/html, ...'
|
||||
string html = new System.Text.RegularExpressions.Regex("^data:text/html,").Replace(uriString, "");
|
||||
browser.NavigateToString(html);
|
||||
}
|
||||
else
|
||||
{
|
||||
browser.Navigate(uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
tests/plugin.xml
Normal file
@@ -0,0 +1,31 @@
|
||||
<?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.themeablebrowser.tests"
|
||||
version="0.6.1-dev">
|
||||
<name>Cordova ThemeableBrowser Plugin Tests</name>
|
||||
<license>Apache 2.0</license>
|
||||
|
||||
<js-module src="tests.js" name="tests">
|
||||
</js-module>
|
||||
|
||||
<asset src="resources" target="cdvtests/iab-resources" />
|
||||
</plugin>
|
||||
21
tests/resources/inject.css
Normal file
@@ -0,0 +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.
|
||||
*/
|
||||
#style-update-file {
|
||||
display: block !important;
|
||||
}
|
||||
44
tests/resources/inject.html
Normal file
@@ -0,0 +1,44 @@
|
||||
<!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">
|
||||
</head>
|
||||
<body id="stage" class="theme">
|
||||
<h1 id="header">ThemeableBrowser - 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() {
|
||||
document.getElementById("u-a").textContent = navigator.userAgent;
|
||||
}
|
||||
updateUserAgent();
|
||||
window.setInterval(updateUserAgent, 1500);
|
||||
</script>
|
||||
</html>
|
||||
20
tests/resources/inject.js
Normal file
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* 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 d = document.getElementById("header")
|
||||
d.innerHTML = "Script file successfully injected";
|
||||
67
tests/resources/local.html
Normal 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 themeableBrowser: 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>
|
||||
BIN
tests/resources/local.pdf
Normal file
42
tests/resources/video.html
Normal file
@@ -0,0 +1,42 @@
|
||||
<!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>
|
||||
|
||||
</head>
|
||||
<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>
|
||||
</html>
|
||||
519
tests/tests.js
Normal file
@@ -0,0 +1,519 @@
|
||||
/*
|
||||
*
|
||||
* 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.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.ThemeableBrowser.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.ThemeableBrowser.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.ThemeableBrowser.open(url, 'random_string', shopt);
|
||||
if (!hiddenwnd) {
|
||||
alert('cordova.ThemeableBrowser.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>ThemeableBrowser</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 ThemeableBrowser with locationBar at top.' +
|
||||
'<p/> <div id="openLocalRandomNoLocation"></div>' +
|
||||
'Expected result: opens successfully in ThemeableBrowser without locationBar.' +
|
||||
'<p/> <div id="openLocalRandomToolBarBottom"></div>' +
|
||||
'Expected result: opens successfully in ThemeableBrowser with locationBar. On iOS the toolbar is at the bottom.' +
|
||||
'<p/> <div id="openLocalRandomToolBarTop"></div>' +
|
||||
'Expected result: opens successfully in ThemeableBrowser with locationBar. On iOS the toolbar is at the top.' +
|
||||
'<p/><div id="openLocalRandomToolBarTopNoLocation"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser 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 ThemeableBrowser to cordova.apache.org' +
|
||||
'<p/> <div id="openWhiteListedRandom"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser to cordova.apache.org' +
|
||||
'<p/> <div id="openWhiteListedRandomNoLocation"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser 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 ThemeableBrowser to apple.com.' +
|
||||
'<p/> <div id="openNonWhiteListedHook"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser to apple.com (using hook of window.open()).' +
|
||||
'<p/> <div id="openNonWhiteListedSelf"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser 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 ThemeableBrowser to apple.com.' +
|
||||
'<p/> <div id="openNonWhiteListedRandom"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser to apple.com.' +
|
||||
'<p/> <div id="openNonWhiteListedRandomNoLocation"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser 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 ThemeableBrowser to https://www.google.co.uk.' +
|
||||
'<p/> <div id="openRedirect302"></div>' +
|
||||
'Expected result: should 302 and open successfully in ThemeableBrowser to www.zhihu.com/answer/16714076.';
|
||||
|
||||
var pdf_url_tests = '<h1>PDF URL</h1>' +
|
||||
'<div id="openPDF"></div>' +
|
||||
'Expected result: ThemeableBrowser opens. PDF should render on iOS.' +
|
||||
'<p/> <div id="openPDFBlank"></div>' +
|
||||
'Expected result: ThemeableBrowser opens. PDF should render on iOS.';
|
||||
|
||||
var invalid_url_tests = '<h1>Invalid URL</h1>' +
|
||||
'<div id="openInvalidScheme"></div>' +
|
||||
'Expected result: fail to load in ThemeableBrowser.' +
|
||||
'<p/> <div id="openInvalidHost"></div>' +
|
||||
'Expected result: fail to load in ThemeableBrowser.' +
|
||||
'<p/> <div id="openInvalidMissing"></div>' +
|
||||
'Expected result: fail to load in ThemeableBrowser (404).';
|
||||
|
||||
var css_js_injection_tests = '<h1>CSS / JS Injection</h1>' +
|
||||
'<div id="openOriginalDocument"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser without text "Style updated from..."' +
|
||||
'<p/> <div id="openCSSInjection"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser with "Style updated from file".' +
|
||||
'<p/> <div id="openCSSInjectionCallback"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser with "Style updated from file", and alert dialog with text "Results verified".' +
|
||||
'<p/> <div id="openCSSLiteralInjection"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser with "Style updated from literal".' +
|
||||
'<p/> <div id="openCSSLiteralInjectionCallback"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser with "Style updated from literal", and alert dialog with text "Results verified".' +
|
||||
'<p/> <div id="openScriptInjection"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser with text "Script file successfully injected".' +
|
||||
'<p/> <div id="openScriptInjectionCallback"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser with text "Script file successfully injected" and alert dialog with the text "Results verified".' +
|
||||
'<p/> <div id="openScriptLiteralInjection"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser with the text "Script literal successfully injected" .' +
|
||||
'<p/> <div id="openScriptLiteralInjectionCallback"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser 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 ThemeableBrowser 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 ThemeableBrowser 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 ThemeableBrowser 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 ThemeableBrowser to the local page, scrolled to the top as normal.' +
|
||||
'<p/> <div id="openAnchor2"></div>' +
|
||||
'Expected result: open successfully in ThemeableBrowser 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');
|
||||
};
|
||||
|
||||
42
www/inappbrowser.css
Normal file
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* 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;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
font-size: 100%;
|
||||
vertical-align: baseline;
|
||||
background: 0 0;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: calc(100% - 80px);
|
||||
height: calc(100% - 80px);
|
||||
z-index: 9999999;
|
||||
border: 40px solid #bfbfbf;
|
||||
border: 40px solid rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.inAppBrowserWrapFullscreen {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
}
|
||||
119
www/themeablebrowser.js
Normal file
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
*
|
||||
* 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');
|
||||
var urlutil = require('cordova/urlutil');
|
||||
|
||||
function ThemeableBrowser() {
|
||||
this.channels = {};
|
||||
}
|
||||
|
||||
ThemeableBrowser.prototype = {
|
||||
_eventHandler: function (event) {
|
||||
if (event && (event.type in this.channels)) {
|
||||
this.channels[event.type].fire(event);
|
||||
}
|
||||
},
|
||||
close: function (eventname) {
|
||||
exec(null, null, 'ThemeableBrowser', 'close', []);
|
||||
return this;
|
||||
},
|
||||
show: function (eventname) {
|
||||
exec(null, null, 'ThemeableBrowser', 'show', []);
|
||||
return this;
|
||||
},
|
||||
reload: function (eventname) {
|
||||
exec(null, null, 'ThemeableBrowser', 'reload', []);
|
||||
return this;
|
||||
},
|
||||
addEventListener: function (eventname,f) {
|
||||
if (!(eventname in this.channels)) {
|
||||
this.channels[eventname] = channel.create(eventname);
|
||||
}
|
||||
this.channels[eventname].subscribe(f);
|
||||
return this;
|
||||
},
|
||||
removeEventListener: function(eventname, f) {
|
||||
if (eventname in this.channels) {
|
||||
this.channels[eventname].unsubscribe(f);
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
executeScript: function(injectDetails, cb) {
|
||||
if (injectDetails.code) {
|
||||
exec(cb, null, 'ThemeableBrowser', 'injectScriptCode', [injectDetails.code, !!cb]);
|
||||
} else if (injectDetails.file) {
|
||||
exec(cb, null, 'ThemeableBrowser', 'injectScriptFile', [injectDetails.file, !!cb]);
|
||||
} else {
|
||||
throw new Error('executeScript requires exactly one of code or file to be specified');
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
insertCSS: function(injectDetails, cb) {
|
||||
if (injectDetails.code) {
|
||||
exec(cb, null, 'ThemeableBrowser', 'injectStyleCode', [injectDetails.code, !!cb]);
|
||||
} else if (injectDetails.file) {
|
||||
exec(cb, null, 'ThemeableBrowser', 'injectStyleFile', [injectDetails.file, !!cb]);
|
||||
} else {
|
||||
throw new Error('insertCSS requires exactly one of code or file to be specified');
|
||||
}
|
||||
return this;
|
||||
}
|
||||
};
|
||||
|
||||
exports.open = 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 ThemeableBrowser();
|
||||
|
||||
callbacks = callbacks || {};
|
||||
for (var callbackName in callbacks) {
|
||||
iab.addEventListener(callbackName, callbacks[callbackName]);
|
||||
}
|
||||
|
||||
var cb = function(eventname) {
|
||||
iab._eventHandler(eventname);
|
||||
};
|
||||
|
||||
strWindowFeatures = strWindowFeatures && JSON.stringify(strWindowFeatures);
|
||||
// Slightly delay the actual native call to give the user a chance to
|
||||
// register event listeners first, otherwise some warnings or errors may be missed.
|
||||
setTimeout(function() {
|
||||
exec(cb, cb, 'ThemeableBrowser', 'open', [strUrl, strWindowName, strWindowFeatures || '']);
|
||||
}, 0);
|
||||
return iab;
|
||||
};
|
||||
|
||||
exports.EVT_ERR = 'ThemeableBrowserError';
|
||||
exports.EVT_WRN = 'ThemeableBrowserWarning';
|
||||
exports.ERR_CRITICAL = 'critical';
|
||||
exports.ERR_LOADFAIL = 'loadfail';
|
||||
exports.WRN_UNEXPECTED = 'unexpected';
|
||||
exports.WRN_UNDEFINED = 'undefined';
|
||||
111
www/windows8/InAppBrowserProxy.js
Normal 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.
|
||||
*
|
||||
*/
|
||||
|
||||
/*jslint sloppy:true */
|
||||
/*global Windows:true, require, document, setTimeout, window, module */
|
||||
|
||||
|
||||
|
||||
var cordova = require('cordova'),
|
||||
channel = require('cordova/channel');
|
||||
|
||||
var browserWrap;
|
||||
|
||||
var IAB = {
|
||||
|
||||
close: function (win, lose) {
|
||||
if (browserWrap) {
|
||||
browserWrap.parentNode.removeChild(browserWrap);
|
||||
browserWrap = null;
|
||||
}
|
||||
},
|
||||
show: function (win, lose) {
|
||||
/* empty block, ran out of bacon?
|
||||
if (browserWrap) {
|
||||
|
||||
}*/
|
||||
},
|
||||
open: function (win, lose, args) {
|
||||
var strUrl = args[0],
|
||||
target = args[1],
|
||||
features = args[2],
|
||||
url,
|
||||
elem;
|
||||
|
||||
if (target === "_system") {
|
||||
url = new Windows.Foundation.Uri(strUrl);
|
||||
Windows.System.Launcher.launchUriAsync(url);
|
||||
} else if (target === "_blank") {
|
||||
if (!browserWrap) {
|
||||
browserWrap = document.createElement("div");
|
||||
browserWrap.style.position = "absolute";
|
||||
browserWrap.style.width = (window.innerWidth - 80) + "px";
|
||||
browserWrap.style.height = (window.innerHeight - 80) + "px";
|
||||
browserWrap.style.borderWidth = "40px";
|
||||
browserWrap.style.borderStyle = "solid";
|
||||
browserWrap.style.borderColor = "rgba(0,0,0,0.25)";
|
||||
|
||||
browserWrap.onclick = function () {
|
||||
setTimeout(function () {
|
||||
IAB.close();
|
||||
}, 0);
|
||||
};
|
||||
|
||||
document.body.appendChild(browserWrap);
|
||||
}
|
||||
|
||||
elem = document.createElement("iframe");
|
||||
elem.style.width = (window.innerWidth - 80) + "px";
|
||||
elem.style.height = (window.innerHeight - 80) + "px";
|
||||
elem.style.borderWidth = "0px";
|
||||
elem.name = "targetFrame";
|
||||
elem.src = strUrl;
|
||||
|
||||
window.addEventListener("resize", function () {
|
||||
if (browserWrap && elem) {
|
||||
elem.style.width = (window.innerWidth - 80) + "px";
|
||||
elem.style.height = (window.innerHeight - 80) + "px";
|
||||
}
|
||||
});
|
||||
|
||||
browserWrap.appendChild(elem);
|
||||
} else {
|
||||
window.location = strUrl;
|
||||
}
|
||||
|
||||
//var object = new WinJS.UI.HtmlControl(elem, { uri: strUrl });
|
||||
|
||||
},
|
||||
|
||||
injectScriptCode: function (code, bCB) {
|
||||
|
||||
// "(function(d) { var c = d.createElement('script'); c.src = %@; d.body.appendChild(c); })(document)"
|
||||
},
|
||||
|
||||
injectScriptFile: function (file, bCB) {
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = IAB;
|
||||
|
||||
|
||||
require("cordova/exec/proxy").add("InAppBrowser", module.exports);
|
||||