Compare commits

..

1 Commits

Author SHA1 Message Date
Jan Piotrowski
731d227f14 Revert "remove failing platform"
This reverts commit bdb4656aa3535fb566764ee62c8dd880f7faba3e.
2020-05-09 16:45:48 +02:00
33 changed files with 1513 additions and 5774 deletions

33
.appveyor.yml Normal file
View File

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

View File

@ -15,32 +15,6 @@
# specific language governing permissions and limitations
# under the License.
github:
description: Apache Cordova InAppBrowser Plugin
homepage: https://cordova.apache.org/
labels:
- android
- cordova
- hacktoberfest
- ios
- java
- javascript
- library
- mobile
- nodejs
- objective-c
features:
wiki: false
issues: true
projects: true
enabled_merge_buttons:
squash: true
merge: false
rebase: false
notifications:
commits: commits@cordova.apache.org
issues: issues@cordova.apache.org

View File

@ -1,23 +1,10 @@
# 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.
root: true
extends: '@cordova/eslint-config/browser'
overrides:
- files: [tests/**/*.js]
extends: '@cordova/eslint-config/node-tests'
extends: semistandard
rules:
indent:
- error
- 4
camelcase: off
padded-blocks: off
operator-linebreak: off
no-throw-literal: off

View File

@ -13,8 +13,7 @@ For usage and support questions, please check out the resources below. Thanks!
You can get answers to your usage and support questions about **Apache Cordova** on:
* GitHub Discussions: https://github.com/apache/cordova/discussions
* Slack Community Chat: https://cordova.slack.com (you can sign-up at https://s.apache.org/cordova-slack)
* Slack Community Chat: https://cordova.slack.com (you can sign-up at http://slack.cordova.io/)
* StackOverflow: https://stackoverflow.com/questions/tagged/cordova using the tag `cordova`
---
@ -23,4 +22,6 @@ If you are using a tool that uses Cordova internally, like e.g. Ionic, check the
* **Ionic Framework**
* [Ionic Community Forum](https://forum.ionicframework.com/)
* [Ionic Discord](https://ionic.link/discord)
* [Ionic Worldwide Slack](https://ionicworldwide.herokuapp.com/)
* **PhoneGap**
* [PhoneGap Developer Community](https://forums.adobe.com/community/phonegap)

View File

@ -1,137 +0,0 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
name: Android Testsuite
on:
push:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
pull_request:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
jobs:
test:
name: Android ${{ matrix.versions.android }} Test
runs-on: macos-latest
continue-on-error: true
# hoist configurations to top that are expected to be updated
env:
# Storing a copy of the repo
repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
node-version: 16
# These are the default Java configurations used by most tests.
# To customize these options, add "java-distro" or "java-version" to the strategy matrix with its overriding value.
default_java-distro: temurin
default_java-version: 11
# These are the default Android System Image configurations used by most tests.
# To customize these options, add "system-image-arch" or "system-image-target" to the strategy matrix with its overriding value.
default_system-image-arch: x86_64
default_system-image-target: google_apis # Most system images have a google_api option. Set this as default.
# configurations for each testing strategy (test matrix)
strategy:
matrix:
versions:
# Test the lowest minimum supported APIs
- android: 7
android-api: 24
# Test the last 3-4 supported APIs
- android: 10
android-api: 29
- android: 11
android-api: 30
- android: 12L
android-api: 32
- android: 13
android-api: 33
timeout-minutes: 60
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: ${{ env.node-version }}
- uses: actions/setup-java@v3
env:
java-version: ${{ matrix.versions.java-version == '' && env.default_java-version || matrix.versions.java-version }}
java-distro: ${{ matrix.versions.java-distro == '' && env.default_java-distro || matrix.versions.java-distro }}
with:
distribution: ${{ env.java-distro }}
java-version: ${{ env.java-version }}
- name: Run Environment Information
run: |
node --version
npm --version
java -version
- name: Run npm install
run: |
export PATH="/usr/local/lib/android/sdk/platform-tools":$PATH
export JAVA_HOME=$JAVA_HOME_11_X64
npm i -g cordova@latest
npm ci
- name: Run paramedic install
if: ${{ endswith(env.repo, '/cordova-paramedic') != true }}
run: npm i -g github:apache/cordova-paramedic
- uses: reactivecircus/android-emulator-runner@d94c3fbe4fe6a29e4a5ba47c12fb47677c73656b
env:
system-image-arch: ${{ matrix.versions.system-image-arch == '' && env.default_system-image-arch || matrix.versions.system-image-arch }}
system-image-target: ${{ matrix.versions.system-image-target == '' && env.default_system-image-target || matrix.versions.system-image-target }}
with:
api-level: ${{ matrix.versions.android-api }}
target: ${{ env.system-image-target }}
arch: ${{ env.system-image-arch }}
force-avd-creation: false
disable-animations: false
emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim
script: echo "Pregenerate the AVD before running Paramedic"
- name: Run paramedic tests
uses: reactivecircus/android-emulator-runner@d94c3fbe4fe6a29e4a5ba47c12fb47677c73656b
env:
system-image-arch: ${{ matrix.versions.system-image-arch == '' && env.default_system-image-arch || matrix.versions.system-image-arch }}
system-image-target: ${{ matrix.versions.system-image-target == '' && env.default_system-image-target || matrix.versions.system-image-target }}
test_config: 'android-${{ matrix.versions.android }}.config.json'
# Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed.
test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }}
paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }}
with:
api-level: ${{ matrix.versions.android-api }}
target: ${{ env.system-image-target }}
arch: ${{ env.system-image-arch }}
force-avd-creation: false
disable-animations: false
emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim
script: ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }}

View File

@ -1,73 +0,0 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
name: Chrome Testsuite
on:
push:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
pull_request:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
jobs:
test:
name: Chrome Latest Test
runs-on: ubuntu-latest
# hoist configurations to top that are expected to be updated
env:
# Storing a copy of the repo
repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
node-version: 16
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: ${{ env.node-version }}
- name: Run install xvfb
run: sudo apt-get install xvfb
- name: Run Environment Information
run: |
node --version
npm --version
- name: Run npm install
run: |
npm i -g cordova@latest
npm ci
- name: Run paramedic install
if: ${{ endswith(env.repo, '/cordova-paramedic') != true }}
run: npm i -g github:apache/cordova-paramedic
- name: Run paramedic tests
env:
test_config: 'browser.config.json'
# Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed.
test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }}
paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }}
run: xvfb-run --auto-servernum ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }}

View File

@ -1,101 +0,0 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
name: iOS Testsuite
on:
push:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
pull_request:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
jobs:
test:
name: iOS ${{ matrix.versions.ios-version }} Test
runs-on: ${{ matrix.versions.os-version }}
continue-on-error: true
# hoist configurations to top that are expected to be updated
env:
# Storing a copy of the repo
repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
node-version: 16
# > Starting April 26, 2021, all iOS and iPadOS apps submitted to the App Store must be built with Xcode 12 and the iOS 14 SDK.
# Because of Apple's requirement, listed above, We will only be using the latest Xcode release for testing.
# To customize these options, add "xcode-version" to the strategy matrix with its overriding value.
default_xcode-version: latest-stable
strategy:
matrix:
versions:
- os-version: macos-11
ios-version: 13.x
xcode-version: 11.x
- os-version: macos-11
ios-version: 14.x
xcode-version: 12.x
- os-version: macos-11
ios-version: 15.x
xcode-version: 13.x
- os-version: macos-12
ios-version: 16.x
xcode-version: 14.x
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: ${{ env.node-version }}
- uses: maxim-lobanov/setup-xcode@9a697e2b393340c3cacd97468baa318e4c883d98
env:
xcode-version: ${{ matrix.versions.xcode-version == '' && env.default_xcode-version || matrix.versions.xcode-version }}
with:
xcode-version: ${{ env.xcode-version }}
- name: Run Environment Information
run: |
node --version
npm --version
xcodebuild -version
- name: Run npm install
run: |
npm i -g cordova@latest ios-deploy@latest
npm ci
- name: Run paramedic install
if: ${{ endswith(env.repo, '/cordova-paramedic') != true }}
run: npm i -g github:apache/cordova-paramedic
- name: Run paramedic tests
env:
test_config: 'ios-${{ matrix.versions.ios-version }}.config.json'
# Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed.
test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }}
paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }}
run: ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }}

View File

@ -1,56 +0,0 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
name: Lint Test
on:
push:
paths:
- '**.js'
- '.eslint*'
- '.github/workflow/lint.yml'
pull_request:
paths:
- '**.js'
- '.eslint*'
- '.github/workflow/lint.yml'
jobs:
test:
name: Lint Test
runs-on: ubuntu-latest
env:
node-version: 16
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: ${{ env.node-version }}
- name: Run Environment Information
run: |
node --version
npm --version
- name: Run npm install
run: |
npm ci
- name: Run lint test
run: |
npm run lint

View File

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

120
.travis.yml Normal file
View File

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

124
README.md
View File

@ -21,18 +21,19 @@ description: Open an in-app browser window.
# under the License.
-->
|AppVeyor|Travis CI|
|:-:|:-:|
|[![Build status](https://ci.appveyor.com/api/projects/status/github/apache/cordova-plugin-inappbrowser?branch=master)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-inappbrowser)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-inappbrowser.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-inappbrowser)|
# cordova-plugin-inappbrowser
[![Android Testsuite](https://github.com/apache/cordova-plugin-inappbrowser/actions/workflows/android.yml/badge.svg)](https://github.com/apache/cordova-plugin-inappbrowser/actions/workflows/android.yml) [![Chrome Testsuite](https://github.com/apache/cordova-plugin-inappbrowser/actions/workflows/chrome.yml/badge.svg)](https://github.com/apache/cordova-plugin-inappbrowser/actions/workflows/chrome.yml) [![iOS Testsuite](https://github.com/apache/cordova-plugin-inappbrowser/actions/workflows/ios.yml/badge.svg)](https://github.com/apache/cordova-plugin-inappbrowser/actions/workflows/ios.yml) [![Lint Test](https://github.com/apache/cordova-plugin-inappbrowser/actions/workflows/lint.yml/badge.svg)](https://github.com/apache/cordova-plugin-inappbrowser/actions/workflows/lint.yml)
You can show helpful articles, videos, and web resources inside of your app. Users can view web pages without leaving your app.
> To get a few ideas, check out the [sample](#sample) at the bottom of this page or go straight to the [reference](#reference) content.
This plugin provides a web browser view that displays when calling `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
### `window.open`
@ -67,14 +68,6 @@ simply hook `window.open` during initialization. For example:
window.open = cordova.InAppBrowser.open;
}
### Preferences
#### <b>config.xml</b>
- <b>InAppBrowserStatusBarStyle [iOS only]</b>: (string, options 'lightcontent', 'darkcontent' or 'default'. Defaults to 'default') set text color style for iOS. 'lightcontent' is intended for use on dark backgrounds. 'darkcontent' is only available since iOS 13 and intended for use on light backgrounds.
```xml
<preference name="InAppBrowserStatusBarStyle" value="lightcontent" />
```
## cordova.InAppBrowser.open
Opens a URL in a new `InAppBrowser` instance, the current browser
@ -149,16 +142,24 @@ instance, or the system browser.
- __toolbarposition__: Set to `top` or `bottom` (default is `bottom`). Causes the toolbar to be at the top or bottom of the window.
- __hidespinner__: Set to `yes` or `no` to change the visibility of the loading indicator (defaults to `no`).
Windows supports these additional options:
- __hidden__: set to `yes` to create the browser and load the page, but not show it. The loadstop event fires when loading is complete. Omit or set to `no` (default) to have the browser open and load normally.
- __hardwareback__: works the same way as on Android platform.
- __fullscreen__: set to `yes` to create the browser control without a border around it. Please note that if __location=no__ is also specified, there will be no control presented to user to close IAB window.
### Supported Platforms
- Android
- Browser
- iOS
- OSX
- Windows
### Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
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');
### OSX Quirks
@ -167,16 +168,6 @@ At the moment the only supported target in OSX is `_system`.
`_blank` and `_self` targets are not yet implemented and are ignored silently. Pull requests and patches to get these to work are greatly appreciated.
### iOS Quirks
Since the introduction of iPadOS 13, iPads try to adapt their content mode / user agent for the optimal browsing experience. This may result in iPads having their user agent set to Macintosh, making it hard to detect them as mobile devices using user agent string sniffing. You can change this with the `PreferredContentMode` preference in `config.xml`.
```xml
<preference name="PreferredContentMode" value="mobile" />
```
The example above forces the user agent to contain `iPad`. The other option is to use the value `desktop` to turn the user agent to `Macintosh`.
### Browser Quirks
- Plugin is implemented via iframe,
@ -213,7 +204,6 @@ The object returned from a call to `cordova.InAppBrowser.open` when the target i
- __exit__: event fires when the `InAppBrowser` window is closed.
- __beforeload__: event fires when the `InAppBrowser` decides whether to load an URL or not (only with option `beforeload` set).
- __message__: event fires when the `InAppBrowser` receives a message posted from the page loaded inside the `InAppBrowser` Webview.
- __download__: _(Android Only)_ event fires when the `InAppBrowser` loads a URL that leads in downloading of a file.
- __callback__: the function that executes when the event fires. The function is passed an `InAppBrowserEvent` object as a parameter.
@ -314,56 +304,39 @@ function messageCallBack(params){
}
```
#### Download event Example
Whenever the InAppBrowser receives or locates to a url which leads in downloading a file, the callback assigned to the "download" event is called. The parameter passed to this callback is an object with the the following properties
- **type** _it contains the String value "download" always_
- **url** _The url that leaded to the downloading of file. Basically, the download link of file_
- **userAgent** _User Agent of the webview_
- **contentDisposition** _If the url contains "content-disposition" header, then this property holds the value of that field else this field is empty_
- **contentLength** _If the link of the file allows to obtain file size then this property holds the file size else it contains int value 0_
- **mimetype** _The MIME type of the file_
```
function downloadListener(params){
var url = params.url;
var mimetype = params.mimetype;
var xhr = new XMLHttpRequest();
xhr.open("GET", params.url);
xhr.onload = function() {
var content = xhr.responseText;
};
xhr.send();
}
```
### InAppBrowserEvent Properties
- __type__: the eventname, either `loadstart`, `loadstop`, `loaderror`, `message` or `exit`. _(String)_
- __url__: the URL that was loaded. _(String)_
- __code__: the error code, only in the case of `loaderror`. _(Number)_
- __message__: the error message, only in the case of `loaderror`. _(String)_
- __data__: the message contents , only in the case of `message`. A stringified JSON object. _(String)_
### Supported Platforms
- Android
- Browser
- iOS
- Windows
- OSX
### Browser Quirks
`loadstart`, `loaderror`, `message` events are not fired.
### Windows Quirks
`message` event is not fired.
### Quick Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## InAppBrowser.removeEventListener
@ -381,7 +354,6 @@ function downloadListener(params){
- __loaderror__: event fires when the `InAppBrowser` encounters an error loading a URL.
- __exit__: event fires when the `InAppBrowser` window is closed.
- __message__: event fires when the `InAppBrowser` receives a message posted from the page loaded inside the `InAppBrowser` Webview.
- __download__: _(Android only)_ event fires when the `InAppBrowser` loads a URL that leads in downloading of a file.
- __callback__: the function to execute when the event fires.
The function is passed an `InAppBrowserEvent` object.
@ -391,10 +363,11 @@ The function is passed an `InAppBrowserEvent` object.
- Android
- Browser
- iOS
- Windows
### Quick Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
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);
@ -412,10 +385,11 @@ The function is passed an `InAppBrowserEvent` object.
- Android
- Browser
- iOS
- Windows
### Quick Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## InAppBrowser.show
@ -431,10 +405,11 @@ The function is passed an `InAppBrowserEvent` object.
- Android
- Browser
- iOS
- Windows
### Quick Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'hidden=yes');
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
@ -450,10 +425,11 @@ The function is passed an `InAppBrowserEvent` object.
- Android
- iOS
- Windows
### Quick Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank');
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank');
// some time later...
ref.hide();
@ -481,10 +457,11 @@ The function is passed an `InAppBrowserEvent` object.
- Android
- Browser
- iOS
- Windows
### Quick Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
@ -493,6 +470,10 @@ The function is passed an `InAppBrowserEvent` object.
- only __code__ key is supported.
### Windows Quirks
Due to [MSDN docs](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx) the invoked script can return only string values, otherwise the parameter, passed to __callback__ will be `[null]`.
## InAppBrowser.insertCSS
> Injects CSS into the `InAppBrowser` window. (Only available when the target is set to `'_blank'`)
@ -511,10 +492,11 @@ The function is passed an `InAppBrowserEvent` object.
- Android
- iOS
- Windows
### Quick Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});
@ -696,13 +678,13 @@ iab.open('local-url.html', 'random_string', 'location=no'); // loads in the InAp
```
var iab = cordova.InAppBrowser;
iab.open('https://whitelisted-url.com'); // loads in the Cordova WebView
iab.open('https://whitelisted-url.com', '_self'); // loads in the Cordova WebView
iab.open('https://whitelisted-url.com', '_system'); // loads in the system browser
iab.open('https://whitelisted-url.com', '_blank'); // loads in the InAppBrowser
iab.open('https://whitelisted-url.com', 'random_string'); // loads in the InAppBrowser
iab.open('http://whitelisted-url.com'); // loads in the Cordova WebView
iab.open('http://whitelisted-url.com', '_self'); // loads in the Cordova WebView
iab.open('http://whitelisted-url.com', '_system'); // loads in the system browser
iab.open('http://whitelisted-url.com', '_blank'); // loads in the InAppBrowser
iab.open('http://whitelisted-url.com', 'random_string'); // loads in the InAppBrowser
iab.open('https://whitelisted-url.com', 'random_string', 'location=no'); // loads in the InAppBrowser, no location bar
iab.open('http://whitelisted-url.com', 'random_string', 'location=no'); // loads in the InAppBrowser, no location bar
```
@ -711,11 +693,11 @@ iab.open('https://whitelisted-url.com', 'random_string', 'location=no'); // load
```
var iab = cordova.InAppBrowser;
iab.open('https://url-that-fails-whitelist.com'); // loads in the InAppBrowser
iab.open('https://url-that-fails-whitelist.com', '_self'); // loads in the InAppBrowser
iab.open('https://url-that-fails-whitelist.com', '_system'); // loads in the system browser
iab.open('https://url-that-fails-whitelist.com', '_blank'); // loads in the InAppBrowser
iab.open('https://url-that-fails-whitelist.com', 'random_string'); // loads in the InAppBrowser
iab.open('https://url-that-fails-whitelist.com', 'random_string', 'location=no'); // loads in the InAppBrowser, no location bar
iab.open('http://url-that-fails-whitelist.com'); // loads in the InAppBrowser
iab.open('http://url-that-fails-whitelist.com', '_self'); // loads in the InAppBrowser
iab.open('http://url-that-fails-whitelist.com', '_system'); // loads in the system browser
iab.open('http://url-that-fails-whitelist.com', '_blank'); // loads in the InAppBrowser
iab.open('http://url-that-fails-whitelist.com', 'random_string'); // loads in the InAppBrowser
iab.open('http://url-that-fails-whitelist.com', 'random_string', 'location=no'); // loads in the InAppBrowser, no location bar
```

View File

@ -20,80 +20,6 @@
-->
# Release Notes
### 6.0.0 (Nov 10, 2023)
* [GH-1033](https://github.com/apache/cordova-plugin-inappbrowser/pull/1033) chore: bump to next major release 6.0.0 & update deependencies
* [GH-1032](https://github.com/apache/cordova-plugin-inappbrowser/pull/1032) chore(lint): update eslint config and apply fixes
* [GH-1030](https://github.com/apache/cordova-plugin-inappbrowser/pull/1030) fix!: remove deprecated platforms **Windows** & osx
* [GH-1031](https://github.com/apache/cordova-plugin-inappbrowser/pull/1031) fix(ios): Remove deprecation warnings and old code
* [GH-927](https://github.com/apache/cordova-plugin-inappbrowser/pull/927) fix: explicitly import dependencies, instead of relying on PCH files. This is important in Swift projects, where you cannot use prefix headers.
* [GH-968](https://github.com/apache/cordova-plugin-inappbrowser/pull/968) GH-706 **Android**: Allow permissions requests
* [GH-1029](https://github.com/apache/cordova-plugin-inappbrowser/pull/1029) chore: update asf config
* [GH-1019](https://github.com/apache/cordova-plugin-inappbrowser/pull/1019) feat(android): Download event
* [GH-1020](https://github.com/apache/cordova-plugin-inappbrowser/pull/1020) ci(gh-action): Paramedic CI sync
* [GH-1015](https://github.com/apache/cordova-plugin-inappbrowser/pull/1015) feat(ios): Make WebView inspectable
* [GH-1016](https://github.com/apache/cordova-plugin-inappbrowser/pull/1016) chore: use https urls in tests and `README`
* [GH-1017](https://github.com/apache/cordova-plugin-inappbrowser/pull/1017) chore: Update SUPPORT_QUESTION.md template
* [GH-977](https://github.com/apache/cordova-plugin-inappbrowser/pull/977) fix(docs): missing xml indicator in code block
* [GH-971](https://github.com/apache/cordova-plugin-inappbrowser/pull/971) ci: sync workflow with paramedic
* [GH-964](https://github.com/apache/cordova-plugin-inappbrowser/pull/964) dep(npm): bump package-lock v2 w/ rebuild
* [GH-957](https://github.com/apache/cordova-plugin-inappbrowser/pull/957) ci(android): update java requirement for `cordova-android`@11
* [GH-946](https://github.com/apache/cordova-plugin-inappbrowser/pull/946) fix(android): increase toolbar to 48dp
* [GH-912](https://github.com/apache/cordova-plugin-inappbrowser/pull/912) ci(ios): update workflow w/ **iOS** 15
* [GH-907](https://github.com/apache/cordova-plugin-inappbrowser/pull/907) ci: add action-badge
* [GH-906](https://github.com/apache/cordova-plugin-inappbrowser/pull/906) ci: remove travis & appveyor
* [GH-903](https://github.com/apache/cordova-plugin-inappbrowser/pull/903) ci: add gh-actions workflows
* [GH-861](https://github.com/apache/cordova-plugin-inappbrowser/pull/861) fix(android): add space between default useragent and custom AppendUserAgent
* [GH-881](https://github.com/apache/cordova-plugin-inappbrowser/pull/881) fix(ios): make system open tel, sms, mailto and geo links
### 5.0.0 (Feb 10, 2021)
* [GH-828](https://github.com/apache/cordova-plugin-inappbrowser/pull/828) feat(ios): add `InAppBrowser`StatusBarStyle 'darkcontent' configuration option
* [GH-823](https://github.com/apache/cordova-plugin-inappbrowser/pull/823) chore: bump engines requirements
* [GH-824](https://github.com/apache/cordova-plugin-inappbrowser/pull/824) breaking: cleanup code for old **Android** versions
* [GH-825](https://github.com/apache/cordova-plugin-inappbrowser/pull/825) (ios): rename CDVWKProcessPoolFactory
* [GH-826](https://github.com/apache/cordova-plugin-inappbrowser/pull/826) ci: add node-14.x to workflow
* [GH-821](https://github.com/apache/cordova-plugin-inappbrowser/pull/821) breaking(android): replace magic numbers with **Android**.os.Build constants
* [GH-717](https://github.com/apache/cordova-plugin-inappbrowser/pull/717) ci(ios): remove wkwebview plugin
### 4.1.0 (Nov 17, 2020)
* [GH-792](https://github.com/apache/cordova-plugin-inappbrowser/pull/792) fix(android): Add mitigation strategy for CVE-2020-6506
* [GH-817](https://github.com/apache/cordova-plugin-inappbrowser/pull/817) Updated typings
* [GH-803](https://github.com/apache/cordova-plugin-inappbrowser/pull/803) fix(android): allow compilation in old `cordova-android` versions
* [GH-688](https://github.com/apache/cordova-plugin-inappbrowser/pull/688) (ios): allow to set "preferredContentMode"
* [GH-768](https://github.com/apache/cordova-plugin-inappbrowser/pull/768) ci(travis): update osx xcode image
* add documentation for `InAppBrowser`StatusBarStyle preference
* undo whitespace changes due to editor preferrences
* [GH-728](https://github.com/apache/cordova-plugin-inappbrowser/pull/728) **iOS**: added `InAppBrowser`StatusBarStyle preference
* [GH-767](https://github.com/apache/cordova-plugin-inappbrowser/pull/767) ci(travis): updates **Android** API level
* (ios): Fix incorrect view height from the second open time
* [GH-748](https://github.com/apache/cordova-plugin-inappbrowser/pull/748) chore: adds package-lock file
* [GH-746](https://github.com/apache/cordova-plugin-inappbrowser/pull/746) chore(npm): use short notation in `package.json`
* [GH-747](https://github.com/apache/cordova-plugin-inappbrowser/pull/747) refactor(eslint): use cordova-eslint /w fix
* [GH-737](https://github.com/apache/cordova-plugin-inappbrowser/pull/737) fix(ios): exit event not fired on swipe down
### 4.0.0 (Jun 09, 2020)
* [GH-715](https://github.com/apache/cordova-plugin-inappbrowser/pull/715) (ios): fix regression in 2706f34
* [GH-685](https://github.com/apache/cordova-plugin-inappbrowser/pull/685) chore: update install engines
* [GH-656](https://github.com/apache/cordova-plugin-inappbrowser/pull/656) (ios) Remove fake status bar with hardcoded height to fix issues in **iOS** devices with a notch
* [GH-693](https://github.com/apache/cordova-plugin-inappbrowser/pull/693) fix(ios): Allow loading local html files
* [GH-293](https://github.com/apache/cordova-plugin-inappbrowser/pull/293) **Android**: SSL errors handling in **Android**
* [GH-672](https://github.com/apache/cordova-plugin-inappbrowser/pull/672) fix(ios): prevent statusbar rotation after closing `InAppBrowser`
* chore(asf): update git notification settings
* [GH-669](https://github.com/apache/cordova-plugin-inappbrowser/pull/669) Allow App using `InAppBrowser` to be hosted in a cross-origin iframe
* [GH-600](https://github.com/apache/cordova-plugin-inappbrowser/pull/600) (all platforms): remove "window.open" overwrite
* [GH-670](https://github.com/apache/cordova-plugin-inappbrowser/pull/670) chore: bump version to 4.0.0-dev
* Update CONTRIBUTING.md
* [GH-662](https://github.com/apache/cordova-plugin-inappbrowser/pull/662) docs: replaces outdated transition and presentation style links
* [GH-666](https://github.com/apache/cordova-plugin-inappbrowser/pull/666) chore: remove deprecated orientation methods
* [GH-515](https://github.com/apache/cordova-plugin-inappbrowser/pull/515) Fix incorrect TypeScript typings
* [GH-654](https://github.com/apache/cordova-plugin-inappbrowser/pull/654) add check for openInSystem postNotification
* [GH-659](https://github.com/apache/cordova-plugin-inappbrowser/pull/659) ci: updates Node.js versions
* [GH-658](https://github.com/apache/cordova-plugin-inappbrowser/pull/658) chore(npm): improve ignore list
* [GH-442](https://github.com/apache/cordova-plugin-inappbrowser/pull/442) fix(android): Reset lefttoright if not set
* [GH-648](https://github.com/apache/cordova-plugin-inappbrowser/pull/648) (android) Correcting the documentation regarding lefttoright opt…
* [GH-634](https://github.com/apache/cordova-plugin-inappbrowser/pull/634) (android) Added option to turn on/off fullscreen mode in **Android**
* [GH-616](https://github.com/apache/cordova-plugin-inappbrowser/pull/616) (android) `InAppBrowser`: java.lang.IllegalArgumentException
* [GH-635](https://github.com/apache/cordova-plugin-inappbrowser/pull/635) breaking(ios): remove UIWebView
### 3.2.0 (Jan 04, 2020)
* [GH-503](https://github.com/apache/cordova-plugin-inappbrowser/pull/503) Defensive code to prevent NULL reference exceptions for async
* [GH-584](https://github.com/apache/cordova-plugin-inappbrowser/pull/584) Add compile-time decision for disabling UIWebView

4349
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "cordova-plugin-inappbrowser",
"version": "6.0.1-dev",
"version": "4.0.0-dev",
"description": "Cordova InAppBrowser Plugin",
"types": "./types/index.d.ts",
"cordova": {
@ -8,11 +8,18 @@
"platforms": [
"android",
"browser",
"ios"
"ios",
"osx",
"windows"
]
},
"repository": "github:apache/cordova-plugin-inappbrowser",
"bugs": "https://github.com/apache/cordova-plugin-inappbrowser/issues",
"repository": {
"type": "git",
"url": "https://github.com/apache/cordova-plugin-inappbrowser"
},
"bugs": {
"url": "https://github.com/apache/cordova-plugin-inappbrowser/issues"
},
"keywords": [
"cordova",
"in",
@ -22,11 +29,13 @@
"ecosystem:cordova",
"cordova-android",
"cordova-browser",
"cordova-ios"
"cordova-ios",
"cordova-osx",
"cordova-windows"
],
"scripts": {
"test": "npm run lint",
"lint": "eslint ."
"test": "npm run eslint",
"eslint": "node node_modules/eslint/bin/eslint www && node node_modules/eslint/bin/eslint src && node node_modules/eslint/bin/eslint tests"
},
"engines": {
"cordovaDependencies": {
@ -34,20 +43,6 @@
"cordova": ">=3.1.0"
},
"4.0.0": {
"cordova": ">=3.1.0",
"cordova-ios": ">=4.0.0"
},
"5.0.0": {
"cordova-android": ">=9.0.0",
"cordova-ios": ">=6.0.0",
"cordova": ">=9.0.0"
},
"6.0.1-dev": {
"cordova-android": ">=10.0.0",
"cordova-ios": ">=6.0.0",
"cordova": ">=9.0.0"
},
"7.0.0": {
"cordova": ">100"
}
}
@ -55,6 +50,12 @@
"author": "Apache Software Foundation",
"license": "Apache-2.0",
"devDependencies": {
"@cordova/eslint-config": "^5.0.0"
"eslint": "^4.0.0",
"eslint-config-semistandard": "^11.0.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.3.0",
"eslint-plugin-node": "^5.0.0",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1"
}
}

View File

@ -20,7 +20,7 @@
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="cordova-plugin-inappbrowser"
version="6.0.1-dev">
version="4.0.0-dev">
<name>InAppBrowser</name>
<description>Cordova InAppBrowser Plugin</description>
@ -30,9 +30,7 @@
<issue>https://github.com/apache/cordova-plugin-inappbrowser/issues</issue>
<engines>
<engine name="cordova" version=">=9.0.0"/>
<engine name="cordova-android" version=">=9.0.0" />
<engine name="cordova-ios" version=">=6.0.0" />
<engine name="cordova" version=">=3.1.0" /><!-- Needs cordova/urlutil -->
</engines>
<!-- android -->
@ -91,6 +89,32 @@
<framework src="CoreGraphics.framework" />
</platform>
<!-- osx -->
<platform name="osx">
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
</js-module>
<config-file target="config.xml" parent="/*">
<feature name="InAppBrowser">
<param name="osx-package" value="CDVInAppBrowser" />
</feature>
</config-file>
<header-file src="src/osx/CDVInAppBrowser.h" />
<source-file src="src/osx/CDVInAppBrowser.m" />
</platform>
<!-- windows -->
<platform name="windows">
<js-module src="www/inappbrowser.js" name="inappbrowser">
<clobbers target="cordova.InAppBrowser.open" />
</js-module>
<js-module src="src/windows/InAppBrowserProxy.js" name="InAppBrowserProxy">
<runs />
</js-module>
<asset src="www/inappbrowser.css" target="css/inappbrowser.css" />
</platform>
<!-- browser -->
<platform name="browser">
<js-module src="www/inappbrowser.js" name="inappbrowser">

View File

@ -20,6 +20,7 @@ package org.apache.cordova.inappbrowser;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
@ -29,6 +30,8 @@ import android.provider.Browser;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Color;
import android.net.http.SslError;
import android.net.Uri;
@ -45,6 +48,7 @@ import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
@ -54,7 +58,6 @@ import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.DownloadListener;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
@ -98,7 +101,6 @@ public class InAppBrowser extends CordovaPlugin {
private static final String LOAD_START_EVENT = "loadstart";
private static final String LOAD_STOP_EVENT = "loadstop";
private static final String LOAD_ERROR_EVENT = "loaderror";
private static final String DOWNLOAD_EVENT = "download";
private static final String MESSAGE_EVENT = "message";
private static final String CLEAR_ALL_CACHE = "clearcache";
private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
@ -119,8 +121,6 @@ public class InAppBrowser extends CordovaPlugin {
private static final String BEFORELOAD = "beforeload";
private static final String FULLSCREEN = "fullscreen";
private static final int TOOLBAR_HEIGHT = 48;
private static final List customizableOptions = Arrays.asList(CLOSE_BUTTON_CAPTION, TOOLBAR_COLOR, NAVIGATION_COLOR, CLOSE_BUTTON_COLOR, FOOTER_COLOR);
private InAppBrowserDialog dialog;
@ -136,8 +136,10 @@ public class InAppBrowser extends CordovaPlugin {
private boolean mediaPlaybackRequiresUserGesture = false;
private boolean shouldPauseInAppBrowser = false;
private boolean useWideViewPort = true;
private ValueCallback<Uri[]> mUploadCallback;
private ValueCallback<Uri> mUploadCallback;
private ValueCallback<Uri[]> mUploadCallbackLollipop;
private final static int FILECHOOSER_REQUESTCODE = 1;
private final static int FILECHOOSER_REQUESTCODE_LOLLIPOP = 2;
private String closeButtonCaption = "";
private String closeButtonColor = "";
private boolean leftToRight = false;
@ -274,7 +276,6 @@ public class InAppBrowser extends CordovaPlugin {
((InAppBrowserClient)inAppWebView.getWebViewClient()).waitForBeforeload = false;
}
inAppWebView.loadUrl(url);
}
});
}
@ -413,7 +414,12 @@ public class InAppBrowser extends CordovaPlugin {
@SuppressLint("NewApi")
@Override
public void run() {
inAppWebView.evaluateJavascript(finalScriptToInject, null);
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);
}
}
});
} else {
@ -756,7 +762,8 @@ public class InAppBrowser extends CordovaPlugin {
if (closeButtonColor != "") close.setColorFilter(android.graphics.Color.parseColor(closeButtonColor));
close.setImageDrawable(closeIcon);
close.setScaleType(ImageView.ScaleType.FIT_CENTER);
close.getAdjustViewBounds();
if (Build.VERSION.SDK_INT >= 16)
close.getAdjustViewBounds();
_close = close;
}
@ -765,7 +772,11 @@ public class InAppBrowser extends CordovaPlugin {
if (leftToRight) closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
else closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
_close.setLayoutParams(closeLayoutParams);
_close.setBackground(null);
if (Build.VERSION.SDK_INT >= 16)
_close.setBackground(null);
else
_close.setBackgroundDrawable(null);
_close.setContentDescription("Close Button");
_close.setId(Integer.valueOf(id));
@ -804,7 +815,7 @@ public class InAppBrowser extends CordovaPlugin {
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
//Please, no more black!
toolbar.setBackgroundColor(toolbarColor);
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(TOOLBAR_HEIGHT)));
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));
if (leftToRight) {
toolbar.setHorizontalGravity(Gravity.LEFT);
@ -834,11 +845,15 @@ public class InAppBrowser extends CordovaPlugin {
int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
Drawable backIcon = activityRes.getDrawable(backResId);
if (navigationButtonColor != "") back.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
back.setBackground(null);
if (Build.VERSION.SDK_INT >= 16)
back.setBackground(null);
else
back.setBackgroundDrawable(null);
back.setImageDrawable(backIcon);
back.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
back.getAdjustViewBounds();
if (Build.VERSION.SDK_INT >= 16)
back.getAdjustViewBounds();
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
@ -856,11 +871,15 @@ public class InAppBrowser extends CordovaPlugin {
int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
Drawable fwdIcon = activityRes.getDrawable(fwdResId);
if (navigationButtonColor != "") forward.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
forward.setBackground(null);
if (Build.VERSION.SDK_INT >= 16)
forward.setBackground(null);
else
forward.setBackgroundDrawable(null);
forward.setImageDrawable(fwdIcon);
forward.setScaleType(ImageView.ScaleType.FIT_CENTER);
forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
forward.getAdjustViewBounds();
if (Build.VERSION.SDK_INT >= 16)
forward.getAdjustViewBounds();
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
@ -906,7 +925,7 @@ public class InAppBrowser extends CordovaPlugin {
_footerColor = android.graphics.Color.LTGRAY;
}
footer.setBackgroundColor(_footerColor);
RelativeLayout.LayoutParams footerLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(TOOLBAR_HEIGHT));
RelativeLayout.LayoutParams footerLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44));
footerLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
footer.setLayoutParams(footerLayout);
if (closeButtonCaption != "") footer.setPadding(this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8));
@ -916,20 +935,22 @@ public class InAppBrowser extends CordovaPlugin {
View footerClose = createCloseButton(7);
footer.addView(footerClose);
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));
// File Chooser Implemented ChromeClient
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView) {
// For Android 5.0+
public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
LOG.d(LOG_TAG, "File Chooser 5.0+");
// If callback exists, finish it.
if(mUploadCallback != null) {
mUploadCallback.onReceiveValue(null);
if(mUploadCallbackLollipop != null) {
mUploadCallbackLollipop.onReceiveValue(null);
}
mUploadCallback = filePathCallback;
mUploadCallbackLollipop = filePathCallback;
// Create File Chooser Intent
Intent content = new Intent(Intent.ACTION_GET_CONTENT);
@ -937,9 +958,30 @@ public class InAppBrowser extends CordovaPlugin {
content.setType("*/*");
// Run cordova startActivityForResult
cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE);
cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE_LOLLIPOP);
return true;
}
// For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
LOG.d(LOG_TAG, "File Chooser 4.1+");
// Call file chooser for Android 3.0+
openFileChooser(uploadMsg, acceptType);
}
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType)
{
LOG.d(LOG_TAG, "File Chooser 3.0+");
mUploadCallback = uploadMsg;
Intent content = new Intent(Intent.ACTION_GET_CONTENT);
content.addCategory(Intent.CATEGORY_OPENABLE);
// run startActivityForResult
cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE);
}
});
currentClient = new InAppBrowserClient(thatWebView, edittext, beforeload);
inAppWebView.setWebViewClient(currentClient);
@ -948,30 +990,6 @@ public class InAppBrowser extends CordovaPlugin {
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(showZoomControls);
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
// download event
inAppWebView.setDownloadListener(
new DownloadListener(){
public void onDownloadStart(
String url, String userAgent, String contentDisposition, String mimetype, long contentLength
){
try{
JSONObject succObj = new JSONObject();
succObj.put("type", DOWNLOAD_EVENT);
succObj.put("url",url);
succObj.put("userAgent",userAgent);
succObj.put("contentDisposition",contentDisposition);
succObj.put("mimetype",mimetype);
succObj.put("contentLength",contentLength);
sendUpdate(succObj, true);
}
catch(Exception e){
LOG.e(LOG_TAG,e.getMessage());
}
}
}
);
// Add postMessage interface
class JsObject {
@ -988,8 +1006,10 @@ public class InAppBrowser extends CordovaPlugin {
}
}
settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
inAppWebView.addJavascriptInterface(new JsObject(), "cordova_iab");
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
inAppWebView.addJavascriptInterface(new JsObject(), "cordova_iab");
}
String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
String appendUserAgent = preferences.getString("AppendUserAgent", null);
@ -998,7 +1018,7 @@ public class InAppBrowser extends CordovaPlugin {
settings.setUserAgentString(overrideUserAgent);
}
if (appendUserAgent != null) {
settings.setUserAgentString(settings.getUserAgentString() + " " + appendUserAgent);
settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent);
}
//Toggle whether this is enabled or not!
@ -1017,16 +1037,15 @@ public class InAppBrowser extends CordovaPlugin {
CookieManager.getInstance().removeSessionCookie();
}
// Enable Thirdparty Cookies
CookieManager.getInstance().setAcceptThirdPartyCookies(inAppWebView,true);
// Enable Thirdparty Cookies on >=Android 5.0 device
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(inAppWebView,true);
}
inAppWebView.loadUrl(url);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(useWideViewPort);
// Multiple Windows set to true to mitigate Chromium security bug.
// See: https://bugs.chromium.org/p/chromium/issues/detail?id=1083819
inAppWebView.getSettings().setSupportMultipleWindows(true);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
@ -1109,14 +1128,32 @@ public class InAppBrowser extends CordovaPlugin {
* @param intent the data from android file chooser
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
LOG.d(LOG_TAG, "onActivityResult");
// If RequestCode or Callback is Invalid
if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) {
super.onActivityResult(requestCode, resultCode, intent);
return;
// For Android >= 5.0
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
LOG.d(LOG_TAG, "onActivityResult (For Android >= 5.0)");
// If RequestCode or Callback is Invalid
if(requestCode != FILECHOOSER_REQUESTCODE_LOLLIPOP || mUploadCallbackLollipop == null) {
super.onActivityResult(requestCode, resultCode, intent);
return;
}
mUploadCallbackLollipop.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
mUploadCallbackLollipop = null;
}
// For Android < 5.0
else {
LOG.d(LOG_TAG, "onActivityResult (For Android < 5.0)");
// If RequestCode or Callback is Invalid
if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) {
super.onActivityResult(requestCode, resultCode, intent);
return;
}
if (null == mUploadCallback) return;
Uri result = intent == null || resultCode != cordova.getActivity().RESULT_OK ? null : intent.getData();
mUploadCallback.onReceiveValue(result);
mUploadCallback = null;
}
mUploadCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
mUploadCallback = null;
}
/**
@ -1316,13 +1353,28 @@ public class InAppBrowser extends CordovaPlugin {
return false;
}
/**
* Legacy (deprecated in API 21)
* For Android 4.4 and below.
* @param view
* @param url
* @return
*/
@SuppressWarnings("deprecation")
@Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
return shouldInterceptRequest(url, super.shouldInterceptRequest(view, url), null);
}
/**
* New (added in API 21)
* For Android 5.0 and above.
*
* @param view
* @param webView
* @param request
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
return shouldInterceptRequest(request.getUrl().toString(), super.shouldInterceptRequest(view, request), request.getMethod());
@ -1373,10 +1425,16 @@ public class InAppBrowser extends CordovaPlugin {
super.onPageFinished(view, url);
// Set the namespace for postMessage()
injectDeferredObject("window.webkit={messageHandlers:{cordova_iab:cordova_iab}}", null);
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
injectDeferredObject("window.webkit={messageHandlers:{cordova_iab:cordova_iab}}", null);
}
// CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
CookieManager.getInstance().flush();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush();
} else {
CookieSyncManager.getInstance().sync();
}
// https://issues.apache.org/jira/browse/CB-11248
view.clearFocus();

View File

@ -24,17 +24,12 @@ import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Message;
import android.webkit.JsPromptResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.PermissionRequest;
public class InAppChromeClient extends WebChromeClient {
@ -46,13 +41,6 @@ public class InAppChromeClient extends WebChromeClient {
super();
this.webView = webView;
}
public void onPermissionRequest(final PermissionRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
request.grant(request.getResources());
}
}
/**
* Handle database quota exceeded notification.
*
@ -147,44 +135,4 @@ public class InAppChromeClient extends WebChromeClient {
return false;
}
/**
* The InAppWebBrowser WebView is configured to MultipleWindow mode to mitigate a security
* bug found in Chromium prior to version 83.0.4103.106.
* See https://bugs.chromium.org/p/chromium/issues/detail?id=1083819
*
* Valid Urls set to open in new window will be routed back to load in the original WebView.
*
* @param view
* @param isDialog
* @param isUserGesture
* @param resultMsg
* @return
*/
@Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
WebView inAppWebView = view;
final WebViewClient webViewClient =
new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
inAppWebView.loadUrl(request.getUrl().toString());
return true;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
inAppWebView.loadUrl(url);
return true;
}
};
final WebView newWebView = new WebView(view.getContext());
newWebView.setWebViewClient(webViewClient);
final WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
}

View File

@ -17,37 +17,43 @@
* specific language governing permissions and limitations
* under the License.
*
*/
*/
const modulemapper = require('cordova/modulemapper');
var modulemapper = require('cordova/modulemapper');
let browserWrap, popup, navigationButtonsDiv, navigationButtonsDivInner, backButton, forwardButton, closeButton;
var browserWrap,
popup,
navigationButtonsDiv,
navigationButtonsDivInner,
backButton,
forwardButton,
closeButton;
function attachNavigationEvents (element, callback) {
const onError = function () {
var onError = function () {
try {
callback({ type: 'loaderror', url: this.contentWindow.location.href }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal
callback({ type: 'loaderror', url: this.contentWindow.location.href }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
} catch (err) {
// blocked by CORS :\
callback({ type: 'loaderror', url: null }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal
callback({ type: 'loaderror', url: null }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
}
};
element.addEventListener('pageshow', function () {
try {
callback({ type: 'loadstart', url: this.contentWindow.location.href }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal
callback({ type: 'loadstart', url: this.contentWindow.location.href }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
} catch (err) {
// blocked by CORS :\
callback({ type: 'loadstart', url: null }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal
callback({ type: 'loadstart', url: null }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
}
});
element.addEventListener('load', function () {
try {
callback({ type: 'loadstop', url: this.contentWindow.location.href }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal
callback({ type: 'loadstop', url: this.contentWindow.location.href }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
} catch (err) {
// blocked by CORS :\
callback({ type: 'loadstop', url: null }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal
callback({ type: 'loadstop', url: null }, {keepCallback: true}); // eslint-disable-line standard/no-callback-literal
}
});
@ -55,7 +61,7 @@ function attachNavigationEvents (element, callback) {
element.addEventListener('abort', onError);
}
const IAB = {
var IAB = {
close: function (win, lose) {
if (browserWrap) {
// use the "open" function callback so that the exit event is fired properly
@ -74,9 +80,9 @@ const IAB = {
},
open: function (win, lose, args) {
const strUrl = args[0];
const target = args[1];
const features = args[2];
var strUrl = args[0];
var target = args[1];
var features = args[2];
IAB._win = win;
@ -147,9 +153,7 @@ const IAB = {
backButton.innerHTML = '←';
backButton.addEventListener('click', function (e) {
if (popup.canGoBack) {
popup.goBack();
}
if (popup.canGoBack) { popup.goBack(); }
});
forwardButton = document.createElement('button');
@ -160,9 +164,7 @@ const IAB = {
forwardButton.innerHTML = '→';
forwardButton.addEventListener('click', function (e) {
if (popup.canGoForward) {
popup.goForward();
}
if (popup.canGoForward) { popup.goForward(); }
});
closeButton = document.createElement('button');
@ -200,8 +202,8 @@ const IAB = {
},
injectScriptCode: function (win, fail, args) {
const code = args[0];
const hasCallback = args[1];
var code = args[0];
var hasCallback = args[1];
if (browserWrap && popup) {
try {
@ -216,7 +218,7 @@ const IAB = {
},
injectScriptFile: function (win, fail, args) {
const msg = 'Browser cordova-plugin-inappbrowser injectScriptFile is not yet implemented';
var msg = 'Browser cordova-plugin-inappbrowser injectScriptFile is not yet implemented';
console.warn(msg);
if (fail) {
fail(msg);
@ -224,7 +226,7 @@ const IAB = {
},
injectStyleCode: function (win, fail, args) {
const msg = 'Browser cordova-plugin-inappbrowser injectStyleCode is not yet implemented';
var msg = 'Browser cordova-plugin-inappbrowser injectStyleCode is not yet implemented';
console.warn(msg);
if (fail) {
fail(msg);
@ -232,7 +234,7 @@ const IAB = {
},
injectStyleFile: function (win, fail, args) {
const msg = 'Browser cordova-plugin-inappbrowser injectStyleFile is not yet implemented';
var msg = 'Browser cordova-plugin-inappbrowser injectStyleFile is not yet implemented';
console.warn(msg);
if (fail) {
fail(msg);

View File

@ -17,7 +17,6 @@
under the License.
*/
#import <UIKit/UINavigationController.h>
#import <Cordova/CDVScreenOrientationDelegate.h>

View File

@ -19,6 +19,8 @@
#import "CDVInAppBrowserNavigationController.h"
#define STATUSBAR_HEIGHT 20.0
@implementation CDVInAppBrowserNavigationController : UINavigationController
- (void) dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion {
@ -28,6 +30,16 @@
}
- (void) viewDidLoad {
CGRect statusBarFrame = [self invertFrameIfNeeded:[UIApplication sharedApplication].statusBarFrame];
statusBarFrame.size.height = STATUSBAR_HEIGHT;
// simplified from: http://stackoverflow.com/a/25669695/219684
UIToolbar* bgToolbar = [[UIToolbar alloc] initWithFrame:statusBarFrame];
bgToolbar.barStyle = UIBarStyleDefault;
[bgToolbar setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
[self.view addSubview:bgToolbar];
[super viewDidLoad];
}

View File

@ -17,7 +17,6 @@
under the License.
*/
#import <Foundation/Foundation.h>
@interface CDVInAppBrowserOptions : NSObject {}

View File

@ -49,7 +49,7 @@
@end
@interface CDVWKInAppBrowserViewController : UIViewController <CDVScreenOrientationDelegate,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UIAdaptivePresentationControllerDelegate>{
@interface CDVWKInAppBrowserViewController : UIViewController <CDVScreenOrientationDelegate,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>{
@private
CDVInAppBrowserOptions *_browserOptions;
NSDictionary *_settings;

View File

@ -18,8 +18,11 @@
*/
#import "CDVWKInAppBrowser.h"
#import <Cordova/NSDictionary+CordovaPreferences.h>
#import <Cordova/CDVWebViewProcessPoolFactory.h>
#if __has_include("CDVWKProcessPoolFactory.h")
#import "CDVWKProcessPoolFactory.h"
#endif
#import <Cordova/CDVPluginResult.h>
#define kInAppBrowserTargetSelf @"_self"
@ -32,11 +35,17 @@
#define IAB_BRIDGE_NAME @"cordova_iab"
#define TOOLBAR_HEIGHT 44.0
#define STATUSBAR_HEIGHT 20.0
#define LOCATIONBAR_HEIGHT 21.0
#define FOOTER_HEIGHT ((TOOLBAR_HEIGHT) + (LOCATIONBAR_HEIGHT))
#pragma mark CDVWKInAppBrowser
@interface CDVWKInAppBrowser () {
NSInteger _previousStatusBarStyle;
}
@end
@implementation CDVWKInAppBrowser
static CDVWKInAppBrowser* instance = nil;
@ -48,6 +57,7 @@ static CDVWKInAppBrowser* instance = nil;
- (void)pluginInitialize
{
instance = self;
_previousStatusBarStyle = -1;
_callbackIdPattern = nil;
_beforeload = @"";
_waitForBeforeload = NO;
@ -128,27 +138,64 @@ static CDVWKInAppBrowser* instance = nil;
}
if (browserOptions.clearcache) {
// Deletes all cookies
WKHTTPCookieStore* cookieStore = dataStore.httpCookieStore;
[cookieStore getAllCookies:^(NSArray* cookies) {
NSHTTPCookie* cookie;
for(cookie in cookies){
[cookieStore deleteCookie:cookie completionHandler:nil];
}
}];
bool isAtLeastiOS11 = false;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000
if (@available(iOS 11.0, *)) {
isAtLeastiOS11 = true;
}
#endif
if(isAtLeastiOS11){
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000
// Deletes all cookies
WKHTTPCookieStore* cookieStore = dataStore.httpCookieStore;
[cookieStore getAllCookies:^(NSArray* cookies) {
NSHTTPCookie* cookie;
for(cookie in cookies){
[cookieStore deleteCookie:cookie completionHandler:nil];
}
}];
#endif
}else{
// https://stackoverflow.com/a/31803708/777265
// Only deletes domain cookies (not session cookies)
[dataStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes]
completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) {
for (WKWebsiteDataRecord *record in records){
NSSet<NSString*>* dataTypes = record.dataTypes;
if([dataTypes containsObject:WKWebsiteDataTypeCookies]){
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes
forDataRecords:@[record]
completionHandler:^{}];
}
}
}];
}
}
if (browserOptions.clearsessioncache) {
// Deletes session cookies
WKHTTPCookieStore* cookieStore = dataStore.httpCookieStore;
[cookieStore getAllCookies:^(NSArray* cookies) {
NSHTTPCookie* cookie;
for(cookie in cookies){
if(cookie.sessionOnly){
[cookieStore deleteCookie:cookie completionHandler:nil];
bool isAtLeastiOS11 = false;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000
if (@available(iOS 11.0, *)) {
isAtLeastiOS11 = true;
}
#endif
if (isAtLeastiOS11) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000
// Deletes session cookies
WKHTTPCookieStore* cookieStore = dataStore.httpCookieStore;
[cookieStore getAllCookies:^(NSArray* cookies) {
NSHTTPCookie* cookie;
for(cookie in cookies){
if(cookie.sessionOnly){
[cookieStore deleteCookie:cookie completionHandler:nil];
}
}
}
}];
}];
#endif
}else{
NSLog(@"clearsessioncache not available below iOS 11.0");
}
}
if (self.inAppBrowserViewController == nil) {
@ -230,13 +277,20 @@ static CDVWKInAppBrowser* instance = nil;
NSLog(@"Tried to show IAB after it was closed.");
return;
}
if (_previousStatusBarStyle != -1) {
NSLog(@"Tried to show IAB while already shown");
return;
}
if(!initHidden){
_previousStatusBarStyle = [UIApplication sharedApplication].statusBarStyle;
}
__block CDVInAppBrowserNavigationController* nav = [[CDVInAppBrowserNavigationController alloc]
initWithRootViewController:self.inAppBrowserViewController];
nav.orientationDelegate = self.inAppBrowserViewController;
nav.navigationBarHidden = YES;
nav.modalPresentationStyle = self.inAppBrowserViewController.modalPresentationStyle;
nav.presentationController.delegate = self.inAppBrowserViewController;
__weak CDVWKInAppBrowser* weakSelf = self;
@ -253,6 +307,7 @@ static CDVWKInAppBrowser* instance = nil;
strongSelf->tmpWindow = [[UIWindow alloc] initWithFrame:frame];
}
UIViewController *tmpController = [[UIViewController alloc] init];
[strongSelf->tmpWindow setRootViewController:tmpController];
[strongSelf->tmpWindow setWindowLevel:UIWindowLevelNormal];
@ -277,10 +332,17 @@ static CDVWKInAppBrowser* instance = nil;
}
if (_previousStatusBarStyle == -1) {
NSLog(@"Tried to hide IAB while already hidden");
return;
}
_previousStatusBarStyle = [UIApplication sharedApplication].statusBarStyle;
// Run later to avoid the "took a long time" log message.
dispatch_async(dispatch_get_main_queue(), ^{
if (self.inAppBrowserViewController != nil) {
_previousStatusBarStyle = -1;
[self.inAppBrowserViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}
});
@ -290,17 +352,16 @@ static CDVWKInAppBrowser* instance = nil;
{
NSURLRequest* request = [NSURLRequest requestWithURL:url];
// the webview engine itself will filter for this according to <allow-navigation> policy
// in config.xml
// in config.xml for cordova-ios-4.0
[self.webViewEngine loadRequest:request];
}
- (void)openInSystem:(NSURL*)url
{
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
if (!success) {
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];
}
}];
if ([[UIApplication sharedApplication] openURL:url] == NO) {
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];
[[UIApplication sharedApplication] openURL:url];
}
}
- (void)loadAfterBeforeload:(CDVInvokedUrlCommand*)command
@ -477,9 +538,8 @@ static CDVWKInAppBrowser* instance = nil;
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
}
//if is an app store, tel, sms, mailto or geo link, let the system handle it, otherwise it fails to load it
NSArray * allowedSchemes = @[@"itms-appss", @"itms-apps", @"tel", @"sms", @"mailto", @"geo"];
if ([allowedSchemes containsObject:[url scheme]]) {
//if is an app store link, let the system handle it, otherwise it fails to load it
if ([[ url scheme] isEqualToString:@"itms-appss"] || [[ url scheme] isEqualToString:@"itms-apps"]) {
[theWebView stopLoading];
[self openInSystem:url];
shouldStart = NO;
@ -619,6 +679,15 @@ static CDVWKInAppBrowser* instance = nil;
// Based on https://stackoverflow.com/questions/4544489/how-to-remove-a-uiwindow
self->tmpWindow.hidden = YES;
self->tmpWindow = nil;
if (IsAtLeastiOSVersion(@"7.0")) {
if (_previousStatusBarStyle != -1) {
[[UIApplication sharedApplication] setStatusBarStyle:_previousStatusBarStyle];
}
}
_previousStatusBarStyle = -1; // this value was reset before reapplying it. caused statusbar to stay black on ios7
}
@end //CDVWKInAppBrowser
@ -629,7 +698,7 @@ static CDVWKInAppBrowser* instance = nil;
@synthesize currentURL;
CGFloat lastReducedStatusBarHeight = 0.0;
BOOL viewRenderedAtLeastOnce = FALSE;
BOOL isExiting = FALSE;
- (id)initWithBrowserOptions: (CDVInAppBrowserOptions*) browserOptions andSettings:(NSDictionary *)settings
@ -671,49 +740,27 @@ BOOL isExiting = FALSE;
}
configuration.applicationNameForUserAgent = userAgent;
configuration.userContentController = userContentController;
#if __has_include(<Cordova/CDVWebViewProcessPoolFactory.h>)
configuration.processPool = [[CDVWebViewProcessPoolFactory sharedFactory] sharedProcessPool];
#elif __has_include("CDVWKProcessPoolFactory.h")
#if __has_include("CDVWKProcessPoolFactory.h")
configuration.processPool = [[CDVWKProcessPoolFactory sharedFactory] sharedProcessPool];
#endif
[configuration.userContentController addScriptMessageHandler:self name:IAB_BRIDGE_NAME];
//WKWebView options
configuration.allowsInlineMediaPlayback = _browserOptions.allowinlinemediaplayback;
configuration.ignoresViewportScaleLimits = _browserOptions.enableviewportscale;
if(_browserOptions.mediaplaybackrequiresuseraction == YES){
configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeAll;
}else{
configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
if (IsAtLeastiOSVersion(@"10.0")) {
configuration.ignoresViewportScaleLimits = _browserOptions.enableviewportscale;
if(_browserOptions.mediaplaybackrequiresuseraction == YES){
configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeAll;
}else{
configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
}
}else{ // iOS 9
configuration.mediaPlaybackRequiresUserAction = _browserOptions.mediaplaybackrequiresuseraction;
}
if (@available(iOS 13.0, *)) {
NSString *contentMode = [self settingForKey:@"PreferredContentMode"];
if ([contentMode isEqual: @"mobile"]) {
configuration.defaultWebpagePreferences.preferredContentMode = WKContentModeMobile;
} else if ([contentMode isEqual: @"desktop"]) {
configuration.defaultWebpagePreferences.preferredContentMode = WKContentModeDesktop;
}
}
self.webView = [[WKWebView alloc] initWithFrame:webViewBounds configuration:configuration];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 160400
// With the introduction of iOS 16.4 the webview is no longer inspectable by default.
// We'll honor that change for release builds, but will still allow inspection on debug builds by default.
// We also introduce an override option, so consumers can influence this decision in their own build.
if (@available(iOS 16.4, *)) {
#ifdef DEBUG
BOOL allowWebviewInspectionDefault = YES;
#else
BOOL allowWebviewInspectionDefault = NO;
#endif
self.webView.inspectable = [_settings cordovaBoolSettingForKey:@"InspectableWebview" defaultValue:allowWebviewInspectionDefault];
}
#endif
[self.view addSubview:self.webView];
[self.view sendSubviewToBack:self.webView];
@ -737,7 +784,11 @@ BOOL isExiting = FALSE;
self.webView.allowsLinkPreview = NO;
self.webView.allowsBackForwardNavigationGestures = NO;
[self.webView.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000
if (@available(iOS 11.0, *)) {
[self.webView.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
}
#endif
self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.spinner.alpha = 1.000;
@ -845,7 +896,7 @@ BOOL isExiting = FALSE;
[self.toolbar setItems:@[self.closeButton, flexibleSpaceButton, self.backButton, fixedSpaceButton, self.forwardButton]];
}
self.view.backgroundColor = [UIColor clearColor];
self.view.backgroundColor = [UIColor grayColor];
[self.view addSubview:self.toolbar];
[self.view addSubview:self.addressLabel];
[self.view addSubview:self.spinner];
@ -867,7 +918,7 @@ BOOL isExiting = FALSE;
// but, if you want to set this yourself, knock yourself out (we can't set the title for a system Done button, so we have to create a new one)
self.closeButton = nil;
// Initialize with title if title is set, otherwise the title will be 'Done' localized
self.closeButton = title != nil ? [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(close)] : [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(close)];
self.closeButton = title != nil ? [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStyleBordered target:self action:@selector(close)] : [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(close)];
self.closeButton.enabled = YES;
// If color on closebutton is requested then initialize with that that color, otherwise use initialize with default
self.closeButton.tintColor = colorString != nil ? [self colorFromHexString:colorString] : [UIColor colorWithRed:60.0 / 255.0 green:136.0 / 255.0 blue:230.0 / 255.0 alpha:1];
@ -991,6 +1042,7 @@ BOOL isExiting = FALSE;
- (void)viewDidLoad
{
viewRenderedAtLeastOnce = FALSE;
[super viewDidLoad];
}
@ -1005,18 +1057,7 @@ BOOL isExiting = FALSE;
- (UIStatusBarStyle)preferredStatusBarStyle
{
NSString* statusBarStylePreference = [self settingForKey:@"InAppBrowserStatusBarStyle"];
if (statusBarStylePreference && [statusBarStylePreference isEqualToString:@"lightcontent"]) {
return UIStatusBarStyleLightContent;
} else if (statusBarStylePreference && [statusBarStylePreference isEqualToString:@"darkcontent"]) {
if (@available(iOS 13.0, *)) {
return UIStatusBarStyleDarkContent;
} else {
return UIStatusBarStyleDefault;
}
} else {
return UIStatusBarStyleDefault;
}
return UIStatusBarStyleDefault;
}
- (BOOL)prefersStatusBarHidden {
@ -1032,7 +1073,6 @@ BOOL isExiting = FALSE;
// Run later to avoid the "took a long time" log message.
dispatch_async(dispatch_get_main_queue(), ^{
isExiting = TRUE;
lastReducedStatusBarHeight = 0.0;
if ([weakSelf respondsToSelector:@selector(presentingViewController)]) {
[[weakSelf presentingViewController] dismissViewControllerAnimated:YES completion:nil];
} else {
@ -1043,12 +1083,8 @@ BOOL isExiting = FALSE;
- (void)navigateTo:(NSURL*)url
{
if ([url.scheme isEqualToString:@"file"]) {
[self.webView loadFileURL:url allowingReadAccessToURL:url];
} else {
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
- (void)goBack:(id)sender
@ -1063,34 +1099,35 @@ BOOL isExiting = FALSE;
- (void)viewWillAppear:(BOOL)animated
{
if (IsAtLeastiOSVersion(@"7.0") && !viewRenderedAtLeastOnce) {
viewRenderedAtLeastOnce = TRUE;
CGRect viewBounds = [self.webView bounds];
viewBounds.origin.y = STATUSBAR_HEIGHT;
viewBounds.size.height = viewBounds.size.height - STATUSBAR_HEIGHT;
self.webView.frame = viewBounds;
[[UIApplication sharedApplication] setStatusBarStyle:[self preferredStatusBarStyle]];
}
[self rePositionViews];
[super viewWillAppear:animated];
}
//
// On iOS 7 the status bar is part of the view's dimensions, therefore it's height has to be taken into account.
// The height of it could be hardcoded as 20 pixels, but that would assume that the upcoming releases of iOS won't
// change that value.
//
- (float) getStatusBarOffset {
return (float) [[UIApplication sharedApplication] statusBarFrame].size.height;
CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
float statusBarOffset = IsAtLeastiOSVersion(@"7.0") ? MIN(statusBarFrame.size.width, statusBarFrame.size.height) : 0.0;
return statusBarOffset;
}
- (void) rePositionViews {
CGRect viewBounds = [self.webView bounds];
CGFloat statusBarHeight = [self getStatusBarOffset];
// orientation portrait or portraitUpsideDown: status bar is on the top and web view is to be aligned to the bottom of the status bar
// orientation landscapeLeft or landscapeRight: status bar height is 0 in but lets account for it in case things ever change in the future
viewBounds.origin.y = statusBarHeight;
// account for web view height portion that may have been reduced by a previous call to this method
viewBounds.size.height = viewBounds.size.height - statusBarHeight + lastReducedStatusBarHeight;
lastReducedStatusBarHeight = statusBarHeight;
if ((_browserOptions.toolbar) && ([_browserOptions.toolbarposition isEqualToString:kInAppBrowserToolbarBarPositionTop])) {
// if we have to display the toolbar on top of the web view, we need to account for its height
viewBounds.origin.y += TOOLBAR_HEIGHT;
self.toolbar.frame = CGRectMake(self.toolbar.frame.origin.x, statusBarHeight, self.toolbar.frame.size.width, self.toolbar.frame.size.height);
if ([_browserOptions.toolbarposition isEqualToString:kInAppBrowserToolbarBarPositionTop]) {
[self.webView setFrame:CGRectMake(self.webView.frame.origin.x, TOOLBAR_HEIGHT, self.webView.frame.size.width, self.webView.frame.size.height)];
[self.toolbar setFrame:CGRectMake(self.toolbar.frame.origin.x, [self getStatusBarOffset], self.toolbar.frame.size.width, self.toolbar.frame.size.height)];
}
self.webView.frame = viewBounds;
}
// Helper function to convert hex color string to UIColor
@ -1201,23 +1238,4 @@ BOOL isExiting = FALSE;
return 1 << UIInterfaceOrientationPortrait;
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context)
{
[self rePositionViews];
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context)
{
}];
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}
#pragma mark UIAdaptivePresentationControllerDelegate
- (void)presentationControllerWillDismiss:(UIPresentationController *)presentationController {
isExiting = TRUE;
}
@end //CDVWKInAppBrowserViewController

30
src/osx/CDVInAppBrowser.h Normal file
View File

@ -0,0 +1,30 @@
/*
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>
@interface CDVInAppBrowser : CDVPlugin {
}
@property (nonatomic, copy) NSString* callbackId;
- (void)open:(CDVInvokedUrlCommand*)command;
@end

89
src/osx/CDVInAppBrowser.m Normal file
View File

@ -0,0 +1,89 @@
/*
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 "CDVInAppBrowser.h"
#import <Cordova/CDVPluginResult.h>
#define kInAppBrowserTargetSelf @"_self"
#define kInAppBrowserTargetSystem @"_system"
#define kInAppBrowserTargetBlank @"_blank"
@interface CDVInAppBrowser () {
}
@end
@implementation CDVInAppBrowser
- (void)pluginInitialize
{
}
- (BOOL) isSystemUrl:(NSURL*)url
{
if ([[url host] isEqualToString:@"itunes.apple.com"]) {
return YES;
}
return NO;
}
- (void)open:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult;
NSString* url = [command argumentAtIndex:0];
NSString* target = [command argumentAtIndex:1 withDefault:kInAppBrowserTargetSelf];
self.callbackId = command.callbackId;
if (url != nil) {
NSURL* baseUrl = [NSURL URLWithString:url];
NSURL* absoluteUrl = [[NSURL URLWithString:url relativeToURL:baseUrl] absoluteURL];
if ([self isSystemUrl:absoluteUrl]) {
target = kInAppBrowserTargetSystem;
}
if ([target isEqualToString:kInAppBrowserTargetSelf]) {
//[self openInCordovaWebView:absoluteUrl withOptions:options];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not Yet Implemented for OSX: [self openInCordovaWebView:absoluteUrl withOptions:options]"];
} else if ([target isEqualToString:kInAppBrowserTargetSystem]) {
[self openInSystem:absoluteUrl];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
} else { // _blank or anything else
//[self openInInAppBrowser:absoluteUrl withOptions:options];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not Yet Implemented for OSX: [self openInInAppBrowser:absoluteUrl withOptions:options]"];
}
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"incorrect number of arguments"];
}
[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)openInSystem:(NSURL*)url
{
[[NSWorkspace sharedWorkspace] openURL:url];
}
@end

View File

@ -0,0 +1,385 @@
/*
*
* 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, setImmediate */
/* eslint standard/no-callback-literal : 0 */
var cordova = require('cordova');
var urlutil = require('cordova/urlutil');
var browserWrap,
popup,
navigationButtonsDiv,
navigationButtonsDivInner,
backButton,
forwardButton,
closeButton,
bodyOverflowStyle,
navigationEventsCallback,
hardwareBackCallback;
// x-ms-webview is available starting from Windows 8.1 (platformId is 'windows')
// http://msdn.microsoft.com/en-us/library/windows/apps/dn301831.aspx
var isWebViewAvailable = cordova.platformId === 'windows';
function attachNavigationEvents (element, callback) {
if (isWebViewAvailable) {
element.addEventListener('MSWebViewNavigationStarting', function (e) {
callback({ type: 'loadstart', url: e.uri }, {keepCallback: true});
});
element.addEventListener('MSWebViewNavigationCompleted', function (e) {
if (e.isSuccess) {
callback({ type: 'loadstop', url: e.uri }, { keepCallback: true });
} else {
callback({ type: 'loaderror', url: e.uri, code: e.webErrorStatus, message: 'Navigation failed with error code ' + e.webErrorStatus }, { keepCallback: true });
}
});
element.addEventListener('MSWebViewUnviewableContentIdentified', function (e) {
// WebView found the content to be not HTML.
// http://msdn.microsoft.com/en-us/library/windows/apps/dn609716.aspx
callback({ type: 'loaderror', url: e.uri, code: e.webErrorStatus, message: 'Navigation failed with error code ' + e.webErrorStatus }, { keepCallback: true });
});
element.addEventListener('MSWebViewContentLoading', function (e) {
if (navigationButtonsDiv && popup) {
if (popup.canGoBack) {
backButton.removeAttribute('disabled');
} else {
backButton.setAttribute('disabled', 'true');
}
if (popup.canGoForward) {
forwardButton.removeAttribute('disabled');
} else {
forwardButton.setAttribute('disabled', 'true');
}
}
});
} else {
var onError = function () {
callback({ type: 'loaderror', url: this.contentWindow.location }, {keepCallback: true});
};
element.addEventListener('unload', function () {
callback({ type: 'loadstart', url: this.contentWindow.location }, {keepCallback: true});
});
element.addEventListener('load', function () {
callback({ type: 'loadstop', url: this.contentWindow.location }, {keepCallback: true});
});
element.addEventListener('error', onError);
element.addEventListener('abort', onError);
}
}
var IAB = {
close: function (win, lose) {
setImmediate(function () {
if (browserWrap) {
if (navigationEventsCallback) {
navigationEventsCallback({ type: 'exit' });
}
browserWrap.parentNode.removeChild(browserWrap);
// Reset body overflow style to initial value
document.body.style.msOverflowStyle = bodyOverflowStyle;
browserWrap = null;
popup = null;
document.removeEventListener('backbutton', hardwareBackCallback, false);
}
});
},
show: function (win, lose) {
setImmediate(function () {
if (browserWrap) {
browserWrap.style.display = 'block';
}
});
},
hide: function (win, lose) {
if (browserWrap) {
browserWrap.style.display = 'none';
}
},
open: function (win, lose, args) {
// make function async so that we can add navigation events handlers before view is loaded and navigation occured
setImmediate(function () {
var strUrl = args[0];
var target = args[1];
var features = args[2];
var url;
navigationEventsCallback = win;
if (target === '_system') {
url = new Windows.Foundation.Uri(strUrl);
Windows.System.Launcher.launchUriAsync(url);
} else if (target === '_self' || !target) {
window.location = strUrl;
} else {
// "_blank" or anything else
if (!browserWrap) {
var browserWrapStyle = document.createElement('link');
browserWrapStyle.rel = 'stylesheet';
browserWrapStyle.type = 'text/css';
browserWrapStyle.href = urlutil.makeAbsolute('/www/css/inappbrowser.css');
document.head.appendChild(browserWrapStyle);
browserWrap = document.createElement('div');
browserWrap.className = 'inAppBrowserWrap';
if (features.indexOf('fullscreen=yes') > -1) {
browserWrap.classList.add('inAppBrowserWrapFullscreen');
}
// Save body overflow style to be able to reset it back later
bodyOverflowStyle = document.body.style.msOverflowStyle;
browserWrap.onclick = function () {
setTimeout(function () {
IAB.close(navigationEventsCallback);
}, 0);
};
document.body.appendChild(browserWrap);
// Hide scrollbars for the whole body while inappbrowser's window is open
document.body.style.msOverflowStyle = 'none';
}
if (features.indexOf('hidden=yes') !== -1) {
browserWrap.style.display = 'none';
}
popup = document.createElement(isWebViewAvailable ? 'x-ms-webview' : 'iframe');
if (popup instanceof HTMLIFrameElement) { // eslint-disable-line no-undef
// For iframe we need to override bacground color of parent element here
// otherwise pages without background color set will have transparent background
popup.style.backgroundColor = 'white';
}
popup.style.borderWidth = '0px';
popup.style.width = '100%';
popup.style.marginBottom = '-5px';
browserWrap.appendChild(popup);
var closeHandler = function (e) {
setTimeout(function () {
IAB.close(navigationEventsCallback);
}, 0);
};
if (features.indexOf('hardwareback=yes') > -1 || features.indexOf('hardwareback') === -1) {
hardwareBackCallback = function () {
if (browserWrap.style.display === 'none') {
// NOTE: backbutton handlers have to throw an exception in order to prevent
// returning 'true' inside cordova-js, which would mean that the event is handled by user.
// Throwing an exception means that the default/system navigation behavior will take place,
// which is to exit the app if the navigation stack is empty.
throw 'Exit the app'; // eslint-disable-line no-throw-literal
}
if (popup.canGoBack) {
popup.goBack();
} else {
closeHandler();
}
};
} else if (features.indexOf('hardwareback=no') > -1) {
hardwareBackCallback = function () {
if (browserWrap.style.display === 'none') {
// See comment above
throw 'Exit the app'; // eslint-disable-line no-throw-literal
}
closeHandler();
};
}
document.addEventListener('backbutton', hardwareBackCallback, false);
if (features.indexOf('location=yes') !== -1 || features.indexOf('location') === -1) {
popup.style.height = 'calc(100% - 70px)';
navigationButtonsDiv = document.createElement('div');
navigationButtonsDiv.className = 'inappbrowser-app-bar';
navigationButtonsDiv.onclick = function (e) {
e.cancelBubble = true;
};
navigationButtonsDivInner = document.createElement('div');
navigationButtonsDivInner.className = 'inappbrowser-app-bar-inner';
navigationButtonsDivInner.onclick = function (e) {
e.cancelBubble = true;
};
backButton = document.createElement('div');
backButton.innerText = 'back';
backButton.className = 'app-bar-action action-back';
backButton.addEventListener('click', function (e) {
if (popup.canGoBack) { popup.goBack(); }
});
forwardButton = document.createElement('div');
forwardButton.innerText = 'forward';
forwardButton.className = 'app-bar-action action-forward';
forwardButton.addEventListener('click', function (e) {
if (popup.canGoForward) { popup.goForward(); }
});
closeButton = document.createElement('div');
closeButton.innerText = 'close';
closeButton.className = 'app-bar-action action-close';
closeButton.addEventListener('click', closeHandler);
if (!isWebViewAvailable) {
// iframe navigation is not yet supported
backButton.setAttribute('disabled', 'true');
forwardButton.setAttribute('disabled', 'true');
}
navigationButtonsDivInner.appendChild(backButton);
navigationButtonsDivInner.appendChild(forwardButton);
navigationButtonsDivInner.appendChild(closeButton);
navigationButtonsDiv.appendChild(navigationButtonsDivInner);
browserWrap.appendChild(navigationButtonsDiv);
} else {
popup.style.height = '100%';
}
// start listening for navigation events
attachNavigationEvents(popup, navigationEventsCallback);
if (isWebViewAvailable) {
strUrl = strUrl.replace('ms-appx://', 'ms-appx-web://');
}
popup.src = strUrl;
}
});
},
injectScriptCode: function (win, fail, args) {
setImmediate(function () {
var code = args[0];
var hasCallback = args[1];
if (isWebViewAvailable && browserWrap && popup) {
var op = popup.invokeScriptAsync('eval', code);
op.oncomplete = function (e) {
if (hasCallback) {
// return null if event target is unavailable by some reason
var result = (e && e.target) ? [e.target.result] : [null];
win(result);
}
};
op.onerror = function () { };
op.start();
}
});
},
injectScriptFile: function (win, fail, args) {
setImmediate(function () {
var filePath = args[0];
var hasCallback = args[1];
if (filePath) {
filePath = urlutil.makeAbsolute(filePath);
}
if (isWebViewAvailable && browserWrap && popup) {
// CB-12364 getFileFromApplicationUriAsync does not support ms-appx-web
var uri = new Windows.Foundation.Uri(filePath.replace('ms-appx-web:', 'ms-appx:'));
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).done(function (file) {
Windows.Storage.FileIO.readTextAsync(file).done(function (code) {
var op = popup.invokeScriptAsync('eval', code);
op.oncomplete = function (e) {
if (hasCallback) {
var result = [e.target.result];
win(result);
}
};
op.onerror = function () { };
op.start();
});
});
}
});
},
injectStyleCode: function (win, fail, args) {
setImmediate(function () {
var code = args[0];
var hasCallback = args[1];
if (isWebViewAvailable && browserWrap && popup) {
injectCSS(popup, code, hasCallback && win);
}
});
},
injectStyleFile: function (win, fail, args) {
setImmediate(function () {
var filePath = args[0];
var hasCallback = args[1];
filePath = filePath && urlutil.makeAbsolute(filePath);
if (isWebViewAvailable && browserWrap && popup) {
// CB-12364 getFileFromApplicationUriAsync does not support ms-appx-web
var uri = new Windows.Foundation.Uri(filePath.replace('ms-appx-web:', 'ms-appx:'));
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 () {
if (callback) {
callback([]);
}
};
op.onerror = function () { };
op.start();
}
module.exports = IAB;
require('cordova/exec/proxy').add('InAppBrowser', module.exports);

View File

@ -1,6 +1,6 @@
{
"name": "cordova-plugin-inappbrowser-tests",
"version": "6.0.1-dev",
"version": "4.0.0-dev",
"description": "",
"cordova": {
"id": "cordova-plugin-inappbrowser-tests",

View File

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

View File

@ -15,7 +15,6 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
const d = document.getElementById('header');
*/
var d = document.getElementById('header');
d.innerHTML = 'Script file successfully injected';

File diff suppressed because it is too large Load Diff

13
types/index.d.ts vendored
View File

@ -8,12 +8,7 @@
// TypeScript Version: 2.3
type channel = "loadstart" | "loadstop" | "loaderror" | "exit" | "message" | "customscheme";
/**
* The object returned from a call to cordova.InAppBrowser.open.
* NOTE: The InAppBrowser window behaves like a standard web browser, and can't access Cordova APIs.
*/
interface InAppBrowser {
interface Window {
/**
* Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
* @param url The URL to load.
@ -23,7 +18,13 @@ interface InAppBrowser {
* name/value pairs must be separated by a comma. Feature names are case insensitive.
*/
open(url: string, target?: string, options?: string): InAppBrowser;
}
/**
* The object returned from a call to window.open.
* NOTE: The InAppBrowser window behaves like a standard web browser, and can't access Cordova APIs.
*/
interface InAppBrowser extends Window {
onloadstart(type: Event): void;
onloadstop(type: InAppBrowserEvent): void;
onloaderror(type: InAppBrowserEvent): void;

114
www/inappbrowser.css Normal file
View File

@ -0,0 +1,114 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
.inAppBrowserWrap {
margin: 0;
padding: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: 0 0;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999999;
box-sizing: border-box;
border: 40px solid #bfbfbf;
border: 40px solid rgba(0, 0, 0, 0.25);
}
.inAppBrowserWrapFullscreen {
border: 0;
}
.inappbrowser-app-bar {
height: 70px;
background-color: #404040;
z-index: 9999999;
}
.inappbrowser-app-bar-inner {
padding-top: 10px;
height: 60px;
width: 155px;
margin: 0 auto;
background-color: #404040;
z-index: 9999999;
}
.app-bar-action {
width: auto;
height: 40px;
margin-left: 20px;
font-family: "Segoe UI Symbol";
float: left;
color: white;
font-size: 12px;
text-transform: lowercase;
text-align: center;
cursor: default;
}
.app-bar-action[disabled] {
color: gray;
/*disable click*/
pointer-events: none;
}
.app-bar-action::before {
font-size: 28px;
display: block;
height: 36px;
}
/* Back */
.action-back {
margin-left: 0px;
}
.action-back::before {
content: "\E0BA";
}
.action-back:not([disabled]):hover::before {
content: "\E0B3";
}
/* Forward */
.action-forward::before {
content: "\E0AC";
}
.action-forward:not([disabled]):hover::before {
content: "\E0AF";
}
/* Close */
.action-close::before {
content: "\E0C7";
/* close icon is larger so we re-size it to fit other icons */
font-size: 20px;
line-height: 40px;
}
.action-close:not([disabled]):hover::before {
content: "\E0CA";
}

View File

@ -17,30 +17,29 @@
* specific language governing permissions and limitations
* under the License.
*
*/
*/
(function () {
const exec = require('cordova/exec');
const channel = require('cordova/channel');
const modulemapper = require('cordova/modulemapper');
const urlutil = require('cordova/urlutil');
var exec = require('cordova/exec');
var channel = require('cordova/channel');
var modulemapper = require('cordova/modulemapper');
var urlutil = require('cordova/urlutil');
function InAppBrowser () {
this.channels = {
beforeload: channel.create('beforeload'),
loadstart: channel.create('loadstart'),
loadstop: channel.create('loadstop'),
loaderror: channel.create('loaderror'),
exit: channel.create('exit'),
customscheme: channel.create('customscheme'),
message: channel.create('message'),
download: channel.create('download')
'beforeload': channel.create('beforeload'),
'loadstart': channel.create('loadstart'),
'loadstop': channel.create('loadstop'),
'loaderror': channel.create('loaderror'),
'exit': channel.create('exit'),
'customscheme': channel.create('customscheme'),
'message': channel.create('message')
};
}
InAppBrowser.prototype = {
_eventHandler: function (event) {
if (event && event.type in this.channels) {
if (event && (event.type in this.channels)) {
if (event.type === 'beforeload') {
this.channels[event.type].fire(event, this._loadAfterBeforeload);
} else {
@ -90,29 +89,25 @@
} else {
throw new Error('insertCSS requires exactly one of code or file to be specified');
}
},
addDownloadListener: function (success, error) {
exec(success, error, 'InAppBrowser', 'downloadListener');
}
};
module.exports = function (strUrl, strWindowName, strWindowFeatures, callbacks) {
// Don't catch calls that write to existing frames (e.g. named iframes).
if (window.frames && window.frames[strWindowName]) {
const origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
return origOpenFunc.apply(window, arguments);
}
strUrl = urlutil.makeAbsolute(strUrl);
const iab = new InAppBrowser();
var iab = new InAppBrowser();
callbacks = callbacks || {};
for (const callbackName in callbacks) {
for (var callbackName in callbacks) {
iab.addEventListener(callbackName, callbacks[callbackName]);
}
const cb = function (eventname) {
var cb = function (eventname) {
iab._eventHandler(eventname);
};