├── .asf.yaml ├── .eslintrc.yml ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE.md ├── ISSUE_TEMPLATE │ ├── BUG_REPORT.md │ ├── FEATURE_REQUEST.md │ └── SUPPORT_QUESTION.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── android.yml │ ├── chrome.yml │ ├── ios.yml │ └── lint.yml ├── .gitignore ├── .npmignore ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── RELEASENOTES.md ├── package-lock.json ├── package.json ├── plugin.xml ├── src ├── android │ ├── InAppBrowser.java │ ├── InAppBrowserDialog.java │ ├── InAppChromeClient.java │ └── res │ │ └── drawable │ │ ├── ic_action_close.xml │ │ ├── ic_action_more.xml │ │ └── ic_action_previous_item.xml ├── browser │ └── InAppBrowserProxy.js └── ios │ ├── CDVInAppBrowserNavigationController.h │ ├── CDVInAppBrowserNavigationController.m │ ├── CDVInAppBrowserOptions.h │ ├── CDVInAppBrowserOptions.m │ ├── CDVWKInAppBrowser.h │ ├── CDVWKInAppBrowser.m │ ├── CDVWKInAppBrowserUIDelegate.h │ └── CDVWKInAppBrowserUIDelegate.m ├── tests ├── .eslintrc.yml ├── package.json ├── plugin.xml ├── resources │ ├── inject.css │ ├── inject.html │ ├── inject.js │ ├── local.html │ ├── local.pdf │ └── video.html └── tests.js ├── types └── index.d.ts └── www └── inappbrowser.js /.asf.yaml: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | github: 19 | description: Apache Cordova InAppBrowser Plugin 20 | homepage: https://cordova.apache.org/ 21 | 22 | labels: 23 | - android 24 | - cordova 25 | - hacktoberfest 26 | - ios 27 | - java 28 | - javascript 29 | - library 30 | - mobile 31 | - nodejs 32 | - objective-c 33 | 34 | features: 35 | wiki: false 36 | issues: true 37 | projects: true 38 | 39 | enabled_merge_buttons: 40 | squash: true 41 | merge: false 42 | rebase: false 43 | 44 | notifications: 45 | commits: commits@cordova.apache.org 46 | issues: issues@cordova.apache.org 47 | pullrequests_status: issues@cordova.apache.org 48 | pullrequests_comment: issues@cordova.apache.org 49 | -------------------------------------------------------------------------------- /.eslintrc.yml: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | root: true 19 | extends: '@cordova/eslint-config/browser' 20 | 21 | overrides: 22 | - files: [tests/**/*.js] 23 | extends: '@cordova/eslint-config/node-tests' 24 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text eol=lf 2 | 3 | # 4 | ## These files are binary and should be left untouched 5 | # 6 | 7 | # (binary is a macro for -text -diff) 8 | *.png binary 9 | *.jpg binary 10 | *.jpeg binary 11 | *.gif binary 12 | *.ico binary 13 | *.mov binary 14 | *.mp4 binary 15 | *.mp3 binary 16 | *.flv binary 17 | *.fla binary 18 | *.swf binary 19 | *.gz binary 20 | *.zip binary 21 | *.7z binary 22 | *.ttf binary 23 | *.eot binary 24 | *.woff binary 25 | *.pyc binary 26 | *.pdf binary -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 5 | 6 | ### Issue Type 7 | 8 | 9 | - [ ] Bug Report 10 | - [ ] Feature Request 11 | - [ ] Support Question 12 | 13 | ## Description 14 | 15 | ## Information 16 | 17 | 18 | ### Command or Code 19 | 20 | 21 | ### Environment, Platform, Device 22 | 23 | 24 | 25 | 26 | ### Version information 27 | 34 | 35 | 36 | 37 | ## Checklist 38 | 39 | 40 | - [ ] I searched for already existing GitHub issues about this 41 | - [ ] I updated all Cordova tooling to their most recent version 42 | - [ ] I included all the necessary information above 43 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/BUG_REPORT.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🐛 Bug Report 3 | about: If something isn't working as expected. 4 | 5 | --- 6 | 7 | # Bug Report 8 | 9 | ## Problem 10 | 11 | ### What is expected to happen? 12 | 13 | 14 | 15 | ### What does actually happen? 16 | 17 | 18 | 19 | ## Information 20 | 21 | 22 | 23 | 24 | ### Command or Code 25 | 26 | 27 | 28 | 29 | ### Environment, Platform, Device 30 | 31 | 32 | 33 | 34 | ### Version information 35 | 42 | 43 | 44 | 45 | ## Checklist 46 | 47 | 48 | - [ ] I searched for existing GitHub issues 49 | - [ ] I updated all Cordova tooling to most recent version 50 | - [ ] I included all the necessary information above 51 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🚀 Feature Request 3 | about: A suggestion for a new functionality 4 | 5 | --- 6 | 7 | # Feature Request 8 | 9 | ## Motivation Behind Feature 10 | 11 | 12 | 13 | 14 | ## Feature Description 15 | 20 | 21 | 22 | 23 | ## Alternatives or Workarounds 24 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/SUPPORT_QUESTION.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 💬 Support Question 3 | about: If you have a question, please check out our Slack or StackOverflow! 4 | 5 | --- 6 | 7 | 8 | 9 | Apache Cordova uses GitHub Issues as a feature request and bug tracker _only_. 10 | For usage and support questions, please check out the resources below. Thanks! 11 | 12 | --- 13 | 14 | You can get answers to your usage and support questions about **Apache Cordova** on: 15 | 16 | * GitHub Discussions: https://github.com/apache/cordova/discussions 17 | * Slack Community Chat: https://cordova.slack.com (you can sign-up at https://s.apache.org/cordova-slack) 18 | * StackOverflow: https://stackoverflow.com/questions/tagged/cordova using the tag `cordova` 19 | 20 | --- 21 | 22 | If you are using a tool that uses Cordova internally, like e.g. Ionic, check their support channels: 23 | 24 | * **Ionic Framework** 25 | * [Ionic Community Forum](https://forum.ionicframework.com/) 26 | * [Ionic Discord](https://ionic.link/discord) 27 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | ### Platforms affected 10 | 11 | 12 | 13 | ### Motivation and Context 14 | 15 | 16 | 17 | 18 | 19 | ### Description 20 | 21 | 22 | 23 | 24 | ### Testing 25 | 26 | 27 | 28 | 29 | ### Checklist 30 | 31 | - [ ] I've run the tests to see all new and existing tests pass 32 | - [ ] I added automated test coverage as appropriate for this change 33 | - [ ] Commit is prefixed with `(platform)` if this change only applies to one platform (e.g. `(android)`) 34 | - [ ] If this Pull Request resolves an issue, I linked to the issue in the text above (and used the correct [keyword to close issues using keywords](https://help.github.com/articles/closing-issues-using-keywords/)) 35 | - [ ] I've updated the documentation if necessary 36 | -------------------------------------------------------------------------------- /.github/workflows/android.yml: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | name: Android Testsuite 19 | 20 | on: 21 | push: 22 | paths-ignore: 23 | - '**.md' 24 | - 'LICENSE' 25 | - '.eslint*' 26 | pull_request: 27 | paths-ignore: 28 | - '**.md' 29 | - 'LICENSE' 30 | - '.eslint*' 31 | 32 | jobs: 33 | test: 34 | name: Android ${{ matrix.versions.android }} Test 35 | runs-on: macos-latest 36 | continue-on-error: true 37 | 38 | # hoist configurations to top that are expected to be updated 39 | env: 40 | # Storing a copy of the repo 41 | repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }} 42 | 43 | node-version: 16 44 | 45 | # These are the default Java configurations used by most tests. 46 | # To customize these options, add "java-distro" or "java-version" to the strategy matrix with its overriding value. 47 | default_java-distro: temurin 48 | default_java-version: 11 49 | 50 | # These are the default Android System Image configurations used by most tests. 51 | # To customize these options, add "system-image-arch" or "system-image-target" to the strategy matrix with its overriding value. 52 | default_system-image-arch: x86_64 53 | default_system-image-target: google_apis # Most system images have a google_api option. Set this as default. 54 | 55 | # configurations for each testing strategy (test matrix) 56 | strategy: 57 | matrix: 58 | versions: 59 | # Test the lowest minimum supported APIs 60 | - android: 7 61 | android-api: 24 62 | 63 | # Test the last 3-4 supported APIs 64 | - android: 10 65 | android-api: 29 66 | 67 | - android: 11 68 | android-api: 30 69 | 70 | - android: 12L 71 | android-api: 32 72 | 73 | - android: 13 74 | android-api: 33 75 | 76 | timeout-minutes: 60 77 | 78 | steps: 79 | - uses: actions/checkout@v3 80 | - uses: actions/setup-node@v3 81 | with: 82 | node-version: ${{ env.node-version }} 83 | - uses: actions/setup-java@v3 84 | env: 85 | java-version: ${{ matrix.versions.java-version == '' && env.default_java-version || matrix.versions.java-version }} 86 | java-distro: ${{ matrix.versions.java-distro == '' && env.default_java-distro || matrix.versions.java-distro }} 87 | with: 88 | distribution: ${{ env.java-distro }} 89 | java-version: ${{ env.java-version }} 90 | 91 | - name: Run Environment Information 92 | run: | 93 | node --version 94 | npm --version 95 | java -version 96 | 97 | - name: Run npm install 98 | run: | 99 | export PATH="/usr/local/lib/android/sdk/platform-tools":$PATH 100 | export JAVA_HOME=$JAVA_HOME_11_X64 101 | npm i -g cordova@latest 102 | npm ci 103 | 104 | - name: Run paramedic install 105 | if: ${{ endswith(env.repo, '/cordova-paramedic') != true }} 106 | run: npm i -g github:apache/cordova-paramedic 107 | 108 | - uses: reactivecircus/android-emulator-runner@d94c3fbe4fe6a29e4a5ba47c12fb47677c73656b 109 | env: 110 | system-image-arch: ${{ matrix.versions.system-image-arch == '' && env.default_system-image-arch || matrix.versions.system-image-arch }} 111 | system-image-target: ${{ matrix.versions.system-image-target == '' && env.default_system-image-target || matrix.versions.system-image-target }} 112 | with: 113 | api-level: ${{ matrix.versions.android-api }} 114 | target: ${{ env.system-image-target }} 115 | arch: ${{ env.system-image-arch }} 116 | force-avd-creation: false 117 | disable-animations: false 118 | emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim 119 | script: echo "Pregenerate the AVD before running Paramedic" 120 | 121 | - name: Run paramedic tests 122 | uses: reactivecircus/android-emulator-runner@d94c3fbe4fe6a29e4a5ba47c12fb47677c73656b 123 | env: 124 | system-image-arch: ${{ matrix.versions.system-image-arch == '' && env.default_system-image-arch || matrix.versions.system-image-arch }} 125 | system-image-target: ${{ matrix.versions.system-image-target == '' && env.default_system-image-target || matrix.versions.system-image-target }} 126 | test_config: 'android-${{ matrix.versions.android }}.config.json' 127 | # Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed. 128 | test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }} 129 | paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }} 130 | with: 131 | api-level: ${{ matrix.versions.android-api }} 132 | target: ${{ env.system-image-target }} 133 | arch: ${{ env.system-image-arch }} 134 | force-avd-creation: false 135 | disable-animations: false 136 | emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim 137 | script: ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }} 138 | -------------------------------------------------------------------------------- /.github/workflows/chrome.yml: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | name: Chrome Testsuite 19 | 20 | on: 21 | push: 22 | paths-ignore: 23 | - '**.md' 24 | - 'LICENSE' 25 | - '.eslint*' 26 | pull_request: 27 | paths-ignore: 28 | - '**.md' 29 | - 'LICENSE' 30 | - '.eslint*' 31 | 32 | jobs: 33 | test: 34 | name: Chrome Latest Test 35 | runs-on: ubuntu-latest 36 | 37 | # hoist configurations to top that are expected to be updated 38 | env: 39 | # Storing a copy of the repo 40 | repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }} 41 | 42 | node-version: 16 43 | 44 | steps: 45 | - uses: actions/checkout@v3 46 | - uses: actions/setup-node@v3 47 | with: 48 | node-version: ${{ env.node-version }} 49 | 50 | - name: Run install xvfb 51 | run: sudo apt-get install xvfb 52 | 53 | - name: Run Environment Information 54 | run: | 55 | node --version 56 | npm --version 57 | 58 | - name: Run npm install 59 | run: | 60 | npm i -g cordova@latest 61 | npm ci 62 | 63 | - name: Run paramedic install 64 | if: ${{ endswith(env.repo, '/cordova-paramedic') != true }} 65 | run: npm i -g github:apache/cordova-paramedic 66 | 67 | - name: Run paramedic tests 68 | env: 69 | test_config: 'browser.config.json' 70 | # Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed. 71 | test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }} 72 | paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }} 73 | run: xvfb-run --auto-servernum ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }} 74 | -------------------------------------------------------------------------------- /.github/workflows/ios.yml: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | name: iOS Testsuite 19 | 20 | on: 21 | push: 22 | paths-ignore: 23 | - '**.md' 24 | - 'LICENSE' 25 | - '.eslint*' 26 | pull_request: 27 | paths-ignore: 28 | - '**.md' 29 | - 'LICENSE' 30 | - '.eslint*' 31 | 32 | jobs: 33 | test: 34 | name: iOS ${{ matrix.versions.ios-version }} Test 35 | runs-on: ${{ matrix.versions.os-version }} 36 | continue-on-error: true 37 | 38 | # hoist configurations to top that are expected to be updated 39 | env: 40 | # Storing a copy of the repo 41 | repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }} 42 | 43 | node-version: 16 44 | 45 | # > 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. 46 | # Because of Apple's requirement, listed above, We will only be using the latest Xcode release for testing. 47 | # To customize these options, add "xcode-version" to the strategy matrix with its overriding value. 48 | default_xcode-version: latest-stable 49 | 50 | strategy: 51 | matrix: 52 | versions: 53 | - os-version: macos-11 54 | ios-version: 13.x 55 | xcode-version: 11.x 56 | 57 | - os-version: macos-11 58 | ios-version: 14.x 59 | xcode-version: 12.x 60 | 61 | - os-version: macos-11 62 | ios-version: 15.x 63 | xcode-version: 13.x 64 | 65 | - os-version: macos-12 66 | ios-version: 16.x 67 | xcode-version: 14.x 68 | 69 | steps: 70 | - uses: actions/checkout@v2 71 | - uses: actions/setup-node@v2 72 | with: 73 | node-version: ${{ env.node-version }} 74 | - uses: maxim-lobanov/setup-xcode@9a697e2b393340c3cacd97468baa318e4c883d98 75 | env: 76 | xcode-version: ${{ matrix.versions.xcode-version == '' && env.default_xcode-version || matrix.versions.xcode-version }} 77 | with: 78 | xcode-version: ${{ env.xcode-version }} 79 | 80 | - name: Run Environment Information 81 | run: | 82 | node --version 83 | npm --version 84 | xcodebuild -version 85 | 86 | - name: Run npm install 87 | run: | 88 | npm i -g cordova@latest ios-deploy@latest 89 | npm ci 90 | 91 | - name: Run paramedic install 92 | if: ${{ endswith(env.repo, '/cordova-paramedic') != true }} 93 | run: npm i -g github:apache/cordova-paramedic 94 | 95 | - name: Run paramedic tests 96 | env: 97 | test_config: 'ios-${{ matrix.versions.ios-version }}.config.json' 98 | # Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed. 99 | test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }} 100 | paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }} 101 | run: ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }} 102 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | name: Lint Test 19 | 20 | on: 21 | push: 22 | paths: 23 | - '**.js' 24 | - '.eslint*' 25 | - '.github/workflow/lint.yml' 26 | pull_request: 27 | paths: 28 | - '**.js' 29 | - '.eslint*' 30 | - '.github/workflow/lint.yml' 31 | 32 | jobs: 33 | test: 34 | name: Lint Test 35 | runs-on: ubuntu-latest 36 | env: 37 | node-version: 16 38 | 39 | steps: 40 | - uses: actions/checkout@v3 41 | - uses: actions/setup-node@v3 42 | with: 43 | node-version: ${{ env.node-version }} 44 | 45 | - name: Run Environment Information 46 | run: | 47 | node --version 48 | npm --version 49 | 50 | - name: Run npm install 51 | run: | 52 | npm ci 53 | 54 | - name: Run lint test 55 | run: | 56 | npm run lint 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #If ignorance is bliss, then somebody knock the smile off my face 2 | 3 | *.csproj.user 4 | *.suo 5 | *.cache 6 | Thumbs.db 7 | *.DS_Store 8 | 9 | *.bak 10 | *.cache 11 | *.log 12 | *.swp 13 | *.user 14 | *.idea 15 | 16 | node_modules 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .* 2 | tests 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 21 | 22 | # Contributing to Apache Cordova 23 | 24 | Anyone can contribute to Cordova. And we need your contributions. 25 | 26 | There are multiple ways to contribute: report bugs, improve the docs, and 27 | contribute code. 28 | 29 | For instructions on this, start with the 30 | [contribution overview](http://cordova.apache.org/contribute/). 31 | 32 | The details are explained there, but the important items are: 33 | - Check for Github issues that corresponds to your contribution and link or create them if necessary. 34 | - Run the tests so your patch doesn't break existing functionality. 35 | 36 | We look forward to your contributions! 37 | 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Apache Cordova 2 | Copyright 2012 The Apache Software Foundation 3 | 4 | This product includes software developed at 5 | The Apache Software Foundation (http://www.apache.org/). 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Inappbrowser 3 | description: Open an in-app browser window. 4 | --- 5 | 23 | 24 | 25 | # cordova-plugin-inappbrowser 26 | 27 | [![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) 28 | 29 | You can show helpful articles, videos, and web resources inside of your app. Users can view web pages without leaving your app. 30 | 31 | > To get a few ideas, check out the [sample](#sample) at the bottom of this page or go straight to the [reference](#reference) content. 32 | 33 | This plugin provides a web browser view that displays when calling `cordova.InAppBrowser.open()`. 34 | 35 | var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes'); 36 | 37 | ### `window.open` 38 | 39 | The `cordova.InAppBrowser.open()` function is defined to be a drop-in replacement 40 | for the `window.open()` function. Existing `window.open()` calls can use the 41 | InAppBrowser window, by replacing window.open: 42 | 43 | window.open = cordova.InAppBrowser.open; 44 | 45 | If you change the browsers `window.open` function this way, it can have unintended side 46 | effects (especially if this plugin is included only as a dependency of another 47 | plugin). 48 | 49 | The InAppBrowser window behaves like a standard web browser, 50 | and can't access Cordova APIs. For this reason, the InAppBrowser is recommended 51 | if you need to load third-party (untrusted) content, instead of loading that 52 | into the main Cordova webview. The InAppBrowser is not subject to the 53 | whitelist, nor is opening links in the system browser. 54 | 55 | The InAppBrowser provides by default its own GUI controls for the user (back, 56 | forward, done). 57 | 58 | ## Installation 59 | 60 | cordova plugin add cordova-plugin-inappbrowser 61 | 62 | If you want all page loads in your app to go through the InAppBrowser, you can 63 | simply hook `window.open` during initialization. For example: 64 | 65 | document.addEventListener("deviceready", onDeviceReady, false); 66 | function onDeviceReady() { 67 | window.open = cordova.InAppBrowser.open; 68 | } 69 | 70 | ### Preferences 71 | 72 | #### config.xml 73 | - InAppBrowserStatusBarStyle [iOS only]: (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. 74 | ```xml 75 | 76 | ``` 77 | 78 | ## cordova.InAppBrowser.open 79 | 80 | Opens a URL in a new `InAppBrowser` instance, the current browser 81 | instance, or the system browser. 82 | 83 | var ref = cordova.InAppBrowser.open(url, target, options); 84 | 85 | - __ref__: Reference to the `InAppBrowser` window when the target is set to `'_blank'`. _(InAppBrowser)_ 86 | 87 | - __url__: The URL to load _(String)_. Call `encodeURI()` on this if the URL contains Unicode characters. 88 | 89 | - __target__: The target in which to load the URL, an optional parameter that defaults to `_self`. _(String)_ 90 | 91 | - `_self`: Opens in the Cordova WebView if the URL is in the white list, otherwise it opens in the `InAppBrowser`. 92 | - `_blank`: Opens in the `InAppBrowser`. 93 | - `_system`: Opens in the system's web browser. 94 | 95 | - __options__: Options for the `InAppBrowser`. Optional, defaulting to: `location=yes`. _(String)_ 96 | 97 | The `options` string must not contain any blank space, and each feature's name/value pairs must be separated by a comma. Feature names are case insensitive. 98 | 99 | All platforms support: 100 | 101 | - __location__: Set to `yes` or `no` to turn the `InAppBrowser`'s location bar on or off. 102 | 103 | Android supports these additional options: 104 | 105 | - __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. 106 | - __beforeload__: set to enable the `beforeload` event to modify which pages are actually loaded in the browser. Accepted values are `get` to intercept only GET requests, `post` to intercept on POST requests or `yes` to intercept both GET & POST requests. Note that POST requests are not currently supported and will be ignored (if you set `beforeload=post` it will raise an error). 107 | - __clearcache__: set to `yes` to have the browser's cookie cache cleared before the new window is opened 108 | - __clearsessioncache__: set to `yes` to have the session cookie cache cleared before the new window is opened 109 | - __closebuttoncaption__: set to a string to use as the close button's caption instead of a X. Note that you need to localize this value yourself. 110 | - __closebuttoncolor__: set to a valid hex color string, for example: `#00ff00`, and it will change the 111 | close button color from default, regardless of being a text or default X. Only has effect if user has location set to `yes`. 112 | - __footer__: set to `yes` to show a close button in the footer similar to the iOS __Done__ button. 113 | The close button will appear the same as for the header hence use __closebuttoncaption__ and __closebuttoncolor__ to set its properties. 114 | - __footercolor__: set to a valid hex color string, for example `#00ff00` or `#CC00ff00` (`#aarrggbb`) , and it will change the footer color from default. 115 | Only has effect if user has __footer__ set to `yes`. 116 | - __hardwareback__: set to `yes` to use the hardware back button to navigate backwards through the `InAppBrowser`'s history. If there is no previous page, the `InAppBrowser` will close. The default value is `yes`, so you must set it to `no` if you want the back button to simply close the InAppBrowser. 117 | - __hidenavigationbuttons__: set to `yes` to hide the navigation buttons on the location toolbar, only has effect if user has location set to `yes`. The default value is `no`. 118 | - __hideurlbar__: set to `yes` to hide the url bar on the location toolbar, only has effect if user has location set to `yes`. The default value is `no`. 119 | - __navigationbuttoncolor__: set to a valid hex color string, for example: `#00ff00`, and it will change the color of both navigation buttons from default. Only has effect if user has location set to `yes` and not hidenavigationbuttons set to `yes`. 120 | - __toolbarcolor__: set to a valid hex color string, for example: `#00ff00`, and it will change the color the toolbar from default. Only has effect if user has location set to `yes`. 121 | - __lefttoright__: Set to `yes` to swap positions of the navigation buttons and the close button. Specifically, navigation buttons go to the right and close button to the left. Default value is `no`. 122 | - __zoom__: set to `yes` to show Android browser's zoom controls, set to `no` to hide them. Default value is `yes`. 123 | - __mediaPlaybackRequiresUserAction__: Set to `yes` to prevent HTML5 audio or video from autoplaying (defaults to `no`). 124 | - __shouldPauseOnSuspend__: Set to `yes` to make InAppBrowser WebView to pause/resume with the app to stop background audio (this may be required to avoid Google Play issues like described in [CB-11013](https://issues.apache.org/jira/browse/CB-11013)). 125 | - __useWideViewPort__: Sets whether the WebView should enable support for the "viewport" HTML meta tag or should use a wide viewport. When the value of the setting is `no`, the layout width is always set to the width of the WebView control in device-independent (CSS) pixels. When the value is `yes` and the page contains the viewport meta tag, the value of the width specified in the tag is used. If the page does not contain the tag or does not provide a width, then a wide viewport will be used. (defaults to `yes`). 126 | - __fullscreen__: Sets whether the InappBrowser WebView is displayed fullscreen or not. In fullscreen mode, the status bar is hidden. Default value is `yes`. 127 | 128 | iOS supports these additional options: 129 | 130 | - __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. 131 | - __beforeload__: set to enable the `beforeload` event to modify which pages are actually loaded in the browser. Accepted values are `get` to intercept only GET requests, `post` to intercept on POST requests or `yes` to intercept both GET & POST requests. Note that POST requests are not currently supported and will be ignored (if you set `beforeload=post` it will raise an error). 132 | - __clearcache__: set to `yes` to have the browser's cookie cache cleared before the new window is opened 133 | - __clearsessioncache__: set to `yes` to have the session cookie cache cleared before the new window is opened. For WKWebView, requires iOS 11+ on target device. 134 | - __cleardata__: set to `yes` to have the browser's entire local storage cleared (cookies, HTML5 local storage, IndexedDB, etc.) before the new window is opened 135 | - __closebuttoncolor__: set as a valid hex color string, for example: `#00ff00`, to change from the default __Done__ button's color. Only applicable if toolbar is not disabled. 136 | - __closebuttoncaption__: set to a string to use as the __Done__ button's caption. Note that you need to localize this value yourself. 137 | - __disallowoverscroll__: Set to `yes` or `no` (default is `no`). Turns on/off the the bounce of the WKWebView's UIScrollView. 138 | - __hidenavigationbuttons__: set to `yes` or `no` to turn the toolbar navigation buttons on or off (defaults to `no`). Only applicable if toolbar is not disabled. 139 | - __navigationbuttoncolor__: set as a valid hex color string, for example: `#00ff00`, to change from the default color. Only applicable if navigation buttons are visible. 140 | - __toolbar__: set to `yes` or `no` to turn the toolbar on or off for the InAppBrowser (defaults to `yes`) 141 | - __toolbarcolor__: set as a valid hex color string, for example: `#00ff00`, to change from the default color of the toolbar. Only applicable if toolbar is not disabled. 142 | - __toolbartranslucent__: set to `yes` or `no` to make the toolbar translucent(semi-transparent) (defaults to `yes`). Only applicable if toolbar is not disabled. 143 | - __lefttoright__: Set to `yes` to swap positions of the navigation buttons and the close button. Specifically, close button goes to the right and navigation buttons to the left. 144 | - __enableViewportScale__: Set to `yes` or `no` to prevent viewport scaling through a meta tag (defaults to `no`). 145 | - __mediaPlaybackRequiresUserAction__: Set to `yes` to prevent HTML5 audio or video from autoplaying (defaults to `no`). 146 | - __allowInlineMediaPlayback__: Set to `yes` or `no` to allow in-line HTML5 media playback, displaying within the browser window rather than a device-specific playback interface. The HTML's `video` element must also include the `webkit-playsinline` attribute (defaults to `no`). 147 | - __presentationstyle__: Set to `pagesheet`, `formsheet` or `fullscreen` to set the [presentation style](https://developer.apple.com/documentation/uikit/uimodalpresentationstyle) (defaults to `fullscreen`). 148 | - __transitionstyle__: Set to `fliphorizontal`, `crossdissolve` or `coververtical` to set the [transition style](https://developer.apple.com/documentation/uikit/uimodaltransitionstyle) (defaults to `coververtical`). 149 | - __toolbarposition__: Set to `top` or `bottom` (default is `bottom`). Causes the toolbar to be at the top or bottom of the window. 150 | - __hidespinner__: Set to `yes` or `no` to change the visibility of the loading indicator (defaults to `no`). 151 | 152 | 153 | ### Supported Platforms 154 | 155 | - Android 156 | - Browser 157 | - iOS 158 | 159 | ### Example 160 | 161 | var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes'); 162 | var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes'); 163 | 164 | ### OSX Quirks 165 | 166 | At the moment the only supported target in OSX is `_system`. 167 | 168 | `_blank` and `_self` targets are not yet implemented and are ignored silently. Pull requests and patches to get these to work are greatly appreciated. 169 | 170 | ### iOS Quirks 171 | 172 | 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`. 173 | 174 | ```xml 175 | 176 | ``` 177 | 178 | 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`. 179 | 180 | ### Browser Quirks 181 | 182 | - Plugin is implemented via iframe, 183 | 184 | - Navigation history (`back` and `forward` buttons in LocationBar) is not implemented. 185 | 186 | ## InAppBrowser 187 | 188 | The object returned from a call to `cordova.InAppBrowser.open` when the target is set to `'_blank'`. 189 | 190 | ### Methods 191 | 192 | - addEventListener 193 | - removeEventListener 194 | - close 195 | - show 196 | - hide 197 | - executeScript 198 | - insertCSS 199 | 200 | ## InAppBrowser.addEventListener 201 | 202 | > Adds a listener for an event from the `InAppBrowser`. (Only available when the target is set to `'_blank'`) 203 | 204 | ref.addEventListener(eventname, callback); 205 | 206 | - __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_ 207 | 208 | - __eventname__: the event to listen for _(String)_ 209 | 210 | - __loadstart__: event fires when the `InAppBrowser` starts to load a URL. 211 | - __loadstop__: event fires when the `InAppBrowser` finishes loading a URL. 212 | - __loaderror__: event fires when the `InAppBrowser` encounters an error when loading a URL. 213 | - __exit__: event fires when the `InAppBrowser` window is closed. 214 | - __beforeload__: event fires when the `InAppBrowser` decides whether to load an URL or not (only with option `beforeload` set). 215 | - __message__: event fires when the `InAppBrowser` receives a message posted from the page loaded inside the `InAppBrowser` Webview. 216 | - __download__: _(Android Only)_ event fires when the `InAppBrowser` loads a URL that leads in downloading of a file. 217 | 218 | - __callback__: the function that executes when the event fires. The function is passed an `InAppBrowserEvent` object as a parameter. 219 | 220 | ## Example 221 | 222 | ```javascript 223 | 224 | var inAppBrowserRef; 225 | 226 | function showHelp(url) { 227 | 228 | var target = "_blank"; 229 | 230 | var options = "location=yes,hidden=yes,beforeload=yes"; 231 | 232 | inAppBrowserRef = cordova.InAppBrowser.open(url, target, options); 233 | 234 | inAppBrowserRef.addEventListener('loadstart', loadStartCallBack); 235 | 236 | inAppBrowserRef.addEventListener('loadstop', loadStopCallBack); 237 | 238 | inAppBrowserRef.addEventListener('loaderror', loadErrorCallBack); 239 | 240 | inAppBrowserRef.addEventListener('beforeload', beforeloadCallBack); 241 | 242 | inAppBrowserRef.addEventListener('message', messageCallBack); 243 | } 244 | 245 | function loadStartCallBack() { 246 | 247 | $('#status-message').text("loading please wait ..."); 248 | 249 | } 250 | 251 | function loadStopCallBack() { 252 | 253 | if (inAppBrowserRef != undefined) { 254 | 255 | inAppBrowserRef.insertCSS({ code: "body{font-size: 25px;}" }); 256 | 257 | inAppBrowserRef.executeScript({ code: "\ 258 | var message = 'this is the message';\ 259 | var messageObj = {my_message: message};\ 260 | var stringifiedMessageObj = JSON.stringify(messageObj);\ 261 | webkit.messageHandlers.cordova_iab.postMessage(stringifiedMessageObj);" 262 | }); 263 | 264 | $('#status-message').text(""); 265 | 266 | inAppBrowserRef.show(); 267 | } 268 | 269 | } 270 | 271 | function loadErrorCallBack(params) { 272 | 273 | $('#status-message').text(""); 274 | 275 | var scriptErrorMesssage = 276 | "alert('Sorry we cannot open that page. Message from the server is : " 277 | + params.message + "');" 278 | 279 | inAppBrowserRef.executeScript({ code: scriptErrorMesssage }, executeScriptCallBack); 280 | 281 | inAppBrowserRef.close(); 282 | 283 | inAppBrowserRef = undefined; 284 | 285 | } 286 | 287 | function executeScriptCallBack(params) { 288 | 289 | if (params[0] == null) { 290 | 291 | $('#status-message').text( 292 | "Sorry we couldn't open that page. Message from the server is : '" 293 | + params.message + "'"); 294 | } 295 | 296 | } 297 | 298 | function beforeloadCallBack(params, callback) { 299 | 300 | if (params.url.startsWith("http://www.example.com/")) { 301 | 302 | // Load this URL in the inAppBrowser. 303 | callback(params.url); 304 | } else { 305 | 306 | // The callback is not invoked, so the page will not be loaded. 307 | $('#status-message').text("This browser only opens pages on http://www.example.com/"); 308 | } 309 | 310 | } 311 | 312 | function messageCallBack(params){ 313 | $('#status-message').text("message received: "+params.data.my_message); 314 | } 315 | 316 | ``` 317 | #### Download event Example 318 | 319 | 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 320 | 321 | - **type** _it contains the String value "download" always_ 322 | - **url** _The url that leaded to the downloading of file. Basically, the download link of file_ 323 | - **userAgent** _User Agent of the webview_ 324 | - **contentDisposition** _If the url contains "content-disposition" header, then this property holds the value of that field else this field is empty_ 325 | - **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_ 326 | - **mimetype** _The MIME type of the file_ 327 | 328 | ``` 329 | 330 | function downloadListener(params){ 331 | var url = params.url; 332 | var mimetype = params.mimetype; 333 | 334 | var xhr = new XMLHttpRequest(); 335 | xhr.open("GET", params.url); 336 | xhr.onload = function() { 337 | var content = xhr.responseText; 338 | }; 339 | xhr.send(); 340 | 341 | } 342 | 343 | ``` 344 | 345 | 346 | ### InAppBrowserEvent Properties 347 | 348 | - __type__: the eventname, either `loadstart`, `loadstop`, `loaderror`, `message` or `exit`. _(String)_ 349 | - __url__: the URL that was loaded. _(String)_ 350 | - __code__: the error code, only in the case of `loaderror`. _(Number)_ 351 | - __message__: the error message, only in the case of `loaderror`. _(String)_ 352 | - __data__: the message contents , only in the case of `message`. A stringified JSON object. _(String)_ 353 | 354 | ### Supported Platforms 355 | 356 | - Android 357 | - Browser 358 | - iOS 359 | 360 | ### Browser Quirks 361 | 362 | `loadstart`, `loaderror`, `message` events are not fired. 363 | 364 | ### Quick Example 365 | 366 | var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes'); 367 | ref.addEventListener('loadstart', function(event) { alert(event.url); }); 368 | 369 | ## InAppBrowser.removeEventListener 370 | 371 | > Removes a listener for an event from the `InAppBrowser`. (Only available when the target is set to `'_blank'`) 372 | 373 | ref.removeEventListener(eventname, callback); 374 | 375 | - __ref__: reference to the `InAppBrowser` window. _(InAppBrowser)_ 376 | 377 | - __eventname__: the event to stop listening for. _(String)_ 378 | 379 | - __loadstart__: event fires when the `InAppBrowser` starts to load a URL. 380 | - __loadstop__: event fires when the `InAppBrowser` finishes loading a URL. 381 | - __loaderror__: event fires when the `InAppBrowser` encounters an error loading a URL. 382 | - __exit__: event fires when the `InAppBrowser` window is closed. 383 | - __message__: event fires when the `InAppBrowser` receives a message posted from the page loaded inside the `InAppBrowser` Webview. 384 | - __download__: _(Android only)_ event fires when the `InAppBrowser` loads a URL that leads in downloading of a file. 385 | 386 | - __callback__: the function to execute when the event fires. 387 | The function is passed an `InAppBrowserEvent` object. 388 | 389 | ### Supported Platforms 390 | 391 | - Android 392 | - Browser 393 | - iOS 394 | 395 | ### Quick Example 396 | 397 | var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes'); 398 | var myCallback = function(event) { alert(event.url); } 399 | ref.addEventListener('loadstart', myCallback); 400 | ref.removeEventListener('loadstart', myCallback); 401 | 402 | ## InAppBrowser.close 403 | 404 | > Closes the `InAppBrowser` window. 405 | 406 | ref.close(); 407 | 408 | - __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_ 409 | 410 | ### Supported Platforms 411 | 412 | - Android 413 | - Browser 414 | - iOS 415 | 416 | ### Quick Example 417 | 418 | var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes'); 419 | ref.close(); 420 | 421 | ## InAppBrowser.show 422 | 423 | > Displays an InAppBrowser window that was opened hidden. Calling this has no effect if the InAppBrowser was already visible. 424 | 425 | ref.show(); 426 | 427 | - __ref__: reference to the InAppBrowser window (`InAppBrowser`) 428 | 429 | ### Supported Platforms 430 | 431 | - Android 432 | - Browser 433 | - iOS 434 | 435 | ### Quick Example 436 | 437 | var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'hidden=yes'); 438 | // some time later... 439 | ref.show(); 440 | 441 | ## InAppBrowser.hide 442 | 443 | > Hides the InAppBrowser window. Calling this has no effect if the InAppBrowser was already hidden. 444 | 445 | ref.hide(); 446 | 447 | - __ref__: reference to the InAppBrowser window (`InAppBrowser`) 448 | 449 | ### Supported Platforms 450 | 451 | - Android 452 | - iOS 453 | 454 | ### Quick Example 455 | 456 | var ref = cordova.InAppBrowser.open('https://apache.org', '_blank'); 457 | // some time later... 458 | ref.hide(); 459 | 460 | ## InAppBrowser.executeScript 461 | 462 | > Injects JavaScript code into the `InAppBrowser` window. (Only available when the target is set to `'_blank'`) 463 | 464 | ref.executeScript(details, callback); 465 | 466 | - __ref__: reference to the `InAppBrowser` window. _(InAppBrowser)_ 467 | 468 | - __injectDetails__: details of the script to run, specifying either a `file` or `code` key. _(Object)_ 469 | - __file__: URL of the script to inject. 470 | - __code__: Text of the script to inject. 471 | 472 | - __callback__: the function that executes after the JavaScript code is injected. 473 | - If the injected script is of type `code`, the callback executes 474 | with a single parameter, which is the return value of the 475 | script, wrapped in an `Array`. For multi-line scripts, this is 476 | the return value of the last statement, or the last expression 477 | evaluated. 478 | 479 | ### Supported Platforms 480 | 481 | - Android 482 | - Browser 483 | - iOS 484 | 485 | ### Quick Example 486 | 487 | var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes'); 488 | ref.addEventListener('loadstop', function() { 489 | ref.executeScript({file: "myscript.js"}); 490 | }); 491 | 492 | ### Browser Quirks 493 | 494 | - only __code__ key is supported. 495 | 496 | ## InAppBrowser.insertCSS 497 | 498 | > Injects CSS into the `InAppBrowser` window. (Only available when the target is set to `'_blank'`) 499 | 500 | ref.insertCSS(details, callback); 501 | 502 | - __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_ 503 | 504 | - __injectDetails__: details of the script to run, specifying either a `file` or `code` key. _(Object)_ 505 | - __file__: URL of the stylesheet to inject. 506 | - __code__: Text of the stylesheet to inject. 507 | 508 | - __callback__: the function that executes after the CSS is injected. 509 | 510 | ### Supported Platforms 511 | 512 | - Android 513 | - iOS 514 | 515 | ### Quick Example 516 | 517 | var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes'); 518 | ref.addEventListener('loadstop', function() { 519 | ref.insertCSS({file: "mystyles.css"}); 520 | }); 521 | __ 522 | 523 | ## Sample: Show help pages with an InAppBrowser 524 | 525 | You can use this plugin to show helpful documentation pages within your app. Users can view online help documents and then close them without leaving the app. 526 | 527 | Here's a few snippets that show how you do this. 528 | 529 | * [Give users a way to ask for help](#give). 530 | * [Load a help page](#load). 531 | * [Let users know that you're getting their page ready](#let). 532 | * [Show the help page](#show). 533 | * [Handle page errors](#handle). 534 | 535 | ### Give users a way to ask for help 536 | 537 | There's lots of ways to do this in your app. A drop down list is a simple way to do that. 538 | 539 | ```html 540 | 541 | 547 | 548 | ``` 549 | 550 | Gather the users choice in the ``onDeviceReady`` function of the page and then send an appropriate URL to a helper function in some shared library file. Our helper function is named ``showHelp()`` and we'll write that function next. 551 | 552 | ```javascript 553 | 554 | $('#help-select').on('change', function (e) { 555 | 556 | var url; 557 | 558 | switch (this.value) { 559 | 560 | case "article": 561 | url = "https://cordova.apache.org/docs/en/latest/" 562 | + "reference/cordova-plugin-inappbrowser/index.html"; 563 | break; 564 | 565 | case "video": 566 | url = "https://youtu.be/F-GlVrTaeH0"; 567 | break; 568 | 569 | case "search": 570 | url = "https://www.google.com/#q=inAppBrowser+plugin"; 571 | break; 572 | } 573 | 574 | showHelp(url); 575 | 576 | }); 577 | 578 | ``` 579 | 580 | ### Load a help page 581 | 582 | We'll use the ``open`` function to load the help page. We're setting the ``hidden`` property to ``yes`` so that we can show the browser only after the page content has loaded. That way, users don't see a blank browser while they wait for content to appear. When the ``loadstop`` event is raised, we'll know when the content has loaded. We'll handle that event shortly. 583 | 584 | ```javascript 585 | 586 | function showHelp(url) { 587 | 588 | var target = "_blank"; 589 | 590 | var options = "location=yes,hidden=yes"; 591 | 592 | inAppBrowserRef = cordova.InAppBrowser.open(url, target, options); 593 | 594 | inAppBrowserRef.addEventListener('loadstart', loadStartCallBack); 595 | 596 | inAppBrowserRef.addEventListener('loadstop', loadStopCallBack); 597 | 598 | inAppBrowserRef.addEventListener('loaderror', loadErrorCallBack); 599 | 600 | } 601 | 602 | ``` 603 | 604 | ### Let users know that you're getting their page ready 605 | 606 | Because the browser doesn't immediately appear, we can use the ``loadstart`` event to show a status message, progress bar, or other indicator. This assures users that content is on the way. 607 | 608 | ```javascript 609 | 610 | function loadStartCallBack() { 611 | 612 | $('#status-message').text("loading please wait ..."); 613 | 614 | } 615 | 616 | ``` 617 | 618 | ### Show the help page 619 | 620 | When the ``loadstopcallback`` event is raised, we know that the content has loaded and we can make the browser visible. This sort of trick can create the impression of better performance. The truth is that whether you show the browser before content loads or not, the load times are exactly the same. 621 | 622 | ```javascript 623 | 624 | function loadStopCallBack() { 625 | 626 | if (inAppBrowserRef != undefined) { 627 | 628 | inAppBrowserRef.insertCSS({ code: "body{font-size: 25px;}" }); 629 | 630 | $('#status-message').text(""); 631 | 632 | inAppBrowserRef.show(); 633 | } 634 | 635 | } 636 | 637 | ``` 638 | You might have noticed the call to the ``insertCSS`` function. This serves no particular purpose in our scenario. But it gives you an idea of why you might use it. In this case, we're just making sure that the font size of your pages have a certain size. You can use this function to insert any CSS style elements. You can even point to a CSS file in your project. 639 | 640 | ### Handle page errors 641 | 642 | Sometimes a page no longer exists, a script error occurs, or a user lacks permission to view the resource. How or if you handle that situation is completely up to you and your design. You can let the browser show that message or you can present it in another way. 643 | 644 | We'll try to show that error in a message box. We can do that by injecting a script that calls the ``alert`` function. That said, this won't work in browsers on Windows devices so we'll have to look at the parameter of the ``executeScript`` callback function to see if our attempt worked. If it didn't work out for us, we'll just show the error message in a ``
`` on the page. 645 | 646 | ```javascript 647 | 648 | function loadErrorCallBack(params) { 649 | 650 | $('#status-message').text(""); 651 | 652 | var scriptErrorMesssage = 653 | "alert('Sorry we cannot open that page. Message from the server is : " 654 | + params.message + "');" 655 | 656 | inAppBrowserRef.executeScript({ code: scriptErrorMesssage }, executeScriptCallBack); 657 | 658 | inAppBrowserRef.close(); 659 | 660 | inAppBrowserRef = undefined; 661 | 662 | } 663 | 664 | function executeScriptCallBack(params) { 665 | 666 | if (params[0] == null) { 667 | 668 | $('#status-message').text( 669 | "Sorry we couldn't open that page. Message from the server is : '" 670 | + params.message + "'"); 671 | } 672 | 673 | } 674 | 675 | ``` 676 | 677 | ## More Usage Info 678 | 679 | ### Local Urls ( source is in the app package ) 680 | ``` 681 | var iab = cordova.InAppBrowser; 682 | 683 | iab.open('local-url.html'); // loads in the Cordova WebView 684 | iab.open('local-url.html', '_self'); // loads in the Cordova WebView 685 | iab.open('local-url.html', '_system'); // Security error: system browser, but url will not load (iOS) 686 | iab.open('local-url.html', '_blank'); // loads in the InAppBrowser 687 | iab.open('local-url.html', 'random_string'); // loads in the InAppBrowser 688 | iab.open('local-url.html', 'random_string', 'location=no'); // loads in the InAppBrowser, no location bar 689 | 690 | ``` 691 | 692 | 693 | 694 | ### Whitelisted Content 695 | 696 | ``` 697 | var iab = cordova.InAppBrowser; 698 | 699 | iab.open('https://whitelisted-url.com'); // loads in the Cordova WebView 700 | iab.open('https://whitelisted-url.com', '_self'); // loads in the Cordova WebView 701 | iab.open('https://whitelisted-url.com', '_system'); // loads in the system browser 702 | iab.open('https://whitelisted-url.com', '_blank'); // loads in the InAppBrowser 703 | iab.open('https://whitelisted-url.com', 'random_string'); // loads in the InAppBrowser 704 | 705 | iab.open('https://whitelisted-url.com', 'random_string', 'location=no'); // loads in the InAppBrowser, no location bar 706 | 707 | ``` 708 | 709 | ### Urls that are not white-listed 710 | 711 | ``` 712 | var iab = cordova.InAppBrowser; 713 | 714 | iab.open('https://url-that-fails-whitelist.com'); // loads in the InAppBrowser 715 | iab.open('https://url-that-fails-whitelist.com', '_self'); // loads in the InAppBrowser 716 | iab.open('https://url-that-fails-whitelist.com', '_system'); // loads in the system browser 717 | iab.open('https://url-that-fails-whitelist.com', '_blank'); // loads in the InAppBrowser 718 | iab.open('https://url-that-fails-whitelist.com', 'random_string'); // loads in the InAppBrowser 719 | iab.open('https://url-that-fails-whitelist.com', 'random_string', 'location=no'); // loads in the InAppBrowser, no location bar 720 | 721 | ``` 722 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cordova-plugin-inappbrowser", 3 | "version": "6.0.1-dev", 4 | "description": "Cordova InAppBrowser Plugin", 5 | "types": "./types/index.d.ts", 6 | "cordova": { 7 | "id": "cordova-plugin-inappbrowser", 8 | "platforms": [ 9 | "android", 10 | "browser", 11 | "ios" 12 | ] 13 | }, 14 | "repository": "github:apache/cordova-plugin-inappbrowser", 15 | "bugs": "https://github.com/apache/cordova-plugin-inappbrowser/issues", 16 | "keywords": [ 17 | "cordova", 18 | "in", 19 | "app", 20 | "browser", 21 | "inappbrowser", 22 | "ecosystem:cordova", 23 | "cordova-android", 24 | "cordova-browser", 25 | "cordova-ios" 26 | ], 27 | "scripts": { 28 | "test": "npm run lint", 29 | "lint": "eslint ." 30 | }, 31 | "engines": { 32 | "cordovaDependencies": { 33 | "0.2.3": { 34 | "cordova": ">=3.1.0" 35 | }, 36 | "4.0.0": { 37 | "cordova": ">=3.1.0", 38 | "cordova-ios": ">=4.0.0" 39 | }, 40 | "5.0.0": { 41 | "cordova-android": ">=9.0.0", 42 | "cordova-ios": ">=6.0.0", 43 | "cordova": ">=9.0.0" 44 | }, 45 | "6.0.1-dev": { 46 | "cordova-android": ">=10.0.0", 47 | "cordova-ios": ">=6.0.0", 48 | "cordova": ">=9.0.0" 49 | }, 50 | "7.0.0": { 51 | "cordova": ">100" 52 | } 53 | } 54 | }, 55 | "author": "Apache Software Foundation", 56 | "license": "Apache-2.0", 57 | "devDependencies": { 58 | "@cordova/eslint-config": "^5.0.0" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | 20 | 21 | 24 | 25 | InAppBrowser 26 | Cordova InAppBrowser Plugin 27 | Apache 2.0 28 | cordova,in,app,browser,inappbrowser 29 | https://github.com/apache/cordova-plugin-inappbrowser 30 | https://github.com/apache/cordova-plugin-inappbrowser/issues 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /src/android/InAppBrowserDialog.java: -------------------------------------------------------------------------------- 1 | package org.apache.cordova.inappbrowser; 2 | 3 | import android.content.Context; 4 | import android.view.View; 5 | import android.view.ViewGroup; 6 | import android.widget.FrameLayout; 7 | 8 | public class InAppBrowserDialog { 9 | private final Context context; 10 | private final FrameLayout dialogContainer; 11 | boolean isVisible = false; 12 | 13 | public InAppBrowserDialog(Context context) { 14 | this.context = context; 15 | 16 | dialogContainer = new FrameLayout(context); 17 | dialogContainer.setLayoutParams(new FrameLayout.LayoutParams( 18 | ViewGroup.LayoutParams.MATCH_PARENT, 19 | ViewGroup.LayoutParams.MATCH_PARENT 20 | )); 21 | } 22 | 23 | public void setContentView(View contentView) { 24 | FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( 25 | ViewGroup.LayoutParams.MATCH_PARENT, 26 | ViewGroup.LayoutParams.MATCH_PARENT 27 | ); 28 | dialogContainer.removeAllViews(); 29 | dialogContainer.addView(contentView, params); 30 | } 31 | 32 | public void show(Boolean animated) { 33 | if (!isVisible) { 34 | if (dialogContainer.getParent() == null) { 35 | if (animated) { 36 | dialogContainer.setTranslationY(dpToPx(40)); 37 | dialogContainer.setAlpha(0); 38 | 39 | dialogContainer.animate() 40 | .alpha(1) 41 | .translationY(0) 42 | .setDuration(150) 43 | .setListener(null); 44 | } 45 | 46 | ViewGroup rootView = ((ViewGroup) ((android.app.Activity) context).getWindow().getDecorView().getRootView()); 47 | rootView.addView(dialogContainer); 48 | } 49 | 50 | isVisible = true; 51 | dialogContainer.setVisibility(View.VISIBLE); 52 | } 53 | } 54 | 55 | public void hide() { 56 | if (isVisible) { 57 | isVisible = false; 58 | dialogContainer.setVisibility(View.GONE); 59 | } 60 | } 61 | 62 | public void dismiss(Boolean animated) { 63 | if (isVisible && animated) { 64 | dialogContainer.animate() 65 | .alpha(0) 66 | .translationY(dpToPx(40)) 67 | .setDuration(150) 68 | .withEndAction(new Runnable() { 69 | @Override 70 | public void run() { 71 | isVisible = false; 72 | dismiss(true); 73 | } 74 | }); 75 | return; 76 | } 77 | isVisible = false; 78 | dialogContainer.removeAllViews(); 79 | 80 | ViewGroup rootView = ((ViewGroup) ((android.app.Activity) context).getWindow().getDecorView().getRootView()); 81 | if (rootView != null && dialogContainer.getParent() != null) { 82 | rootView.removeView(dialogContainer); 83 | } 84 | } 85 | 86 | public View getView() { 87 | return dialogContainer; 88 | } 89 | 90 | private float dpToPx(int dp) { 91 | return dp * context.getResources().getDisplayMetrics().density; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/android/InAppChromeClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | package org.apache.cordova.inappbrowser; 20 | 21 | import org.apache.cordova.CordovaWebView; 22 | import org.apache.cordova.LOG; 23 | import org.apache.cordova.PluginResult; 24 | import org.json.JSONArray; 25 | import org.json.JSONException; 26 | 27 | import android.annotation.TargetApi; 28 | import android.os.Build; 29 | import android.os.Message; 30 | import android.webkit.JsPromptResult; 31 | import android.webkit.WebChromeClient; 32 | import android.webkit.WebResourceRequest; 33 | import android.webkit.WebStorage; 34 | import android.webkit.WebView; 35 | import android.webkit.WebViewClient; 36 | import android.webkit.GeolocationPermissions.Callback; 37 | import android.webkit.PermissionRequest; 38 | 39 | public class InAppChromeClient extends WebChromeClient { 40 | 41 | private CordovaWebView webView; 42 | private String LOG_TAG = "InAppChromeClient"; 43 | private long MAX_QUOTA = 100 * 1024 * 1024; 44 | 45 | public InAppChromeClient(CordovaWebView webView) { 46 | super(); 47 | this.webView = webView; 48 | } 49 | 50 | public void onPermissionRequest(final PermissionRequest request) { 51 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 52 | request.grant(request.getResources()); 53 | } 54 | } 55 | 56 | /** 57 | * Handle database quota exceeded notification. 58 | * 59 | * @param url 60 | * @param databaseIdentifier 61 | * @param currentQuota 62 | * @param estimatedSize 63 | * @param totalUsedQuota 64 | * @param quotaUpdater 65 | */ 66 | @Override 67 | public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, 68 | long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) 69 | { 70 | LOG.d(LOG_TAG, "onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota); 71 | quotaUpdater.updateQuota(MAX_QUOTA); 72 | } 73 | 74 | /** 75 | * Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin. 76 | * 77 | * @param origin 78 | * @param callback 79 | */ 80 | @Override 81 | public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { 82 | super.onGeolocationPermissionsShowPrompt(origin, callback); 83 | callback.invoke(origin, true, false); 84 | } 85 | 86 | /** 87 | * Tell the client to display a prompt dialog to the user. 88 | * If the client returns true, WebView will assume that the client will 89 | * handle the prompt dialog and call the appropriate JsPromptResult method. 90 | * 91 | * The prompt bridge provided for the InAppBrowser is capable of executing any 92 | * oustanding callback belonging to the InAppBrowser plugin. Care has been 93 | * taken that other callbacks cannot be triggered, and that no other code 94 | * execution is possible. 95 | * 96 | * To trigger the bridge, the prompt default value should be of the form: 97 | * 98 | * gap-iab:// 99 | * 100 | * where is the string id of the callback to trigger (something 101 | * like "InAppBrowser0123456789") 102 | * 103 | * If present, the prompt message is expected to be a JSON-encoded value to 104 | * pass to the callback. A JSON_EXCEPTION is returned if the JSON is invalid. 105 | * 106 | * @param view 107 | * @param url 108 | * @param message 109 | * @param defaultValue 110 | * @param result 111 | */ 112 | @Override 113 | public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { 114 | // See if the prompt string uses the 'gap-iab' protocol. If so, the remainder should be the id of a callback to execute. 115 | if (defaultValue != null && defaultValue.startsWith("gap")) { 116 | if(defaultValue.startsWith("gap-iab://")) { 117 | PluginResult scriptResult; 118 | String scriptCallbackId = defaultValue.substring(10); 119 | if (scriptCallbackId.matches("^InAppBrowser[0-9]{1,10}$")) { 120 | if(message == null || message.length() == 0) { 121 | scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray()); 122 | } else { 123 | try { 124 | scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray(message)); 125 | } catch(JSONException e) { 126 | scriptResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); 127 | } 128 | } 129 | this.webView.sendPluginResult(scriptResult, scriptCallbackId); 130 | result.confirm(""); 131 | return true; 132 | } 133 | else { 134 | // Anything else that doesn't look like InAppBrowser0123456789 should end up here 135 | LOG.w(LOG_TAG, "InAppBrowser callback called with invalid callbackId : "+ scriptCallbackId); 136 | result.cancel(); 137 | return true; 138 | } 139 | } 140 | else { 141 | // Anything else with a gap: prefix should get this message 142 | LOG.w(LOG_TAG, "InAppBrowser does not support Cordova API calls: " + url + " " + defaultValue); 143 | result.cancel(); 144 | return true; 145 | } 146 | } 147 | return false; 148 | } 149 | 150 | /** 151 | * The InAppWebBrowser WebView is configured to MultipleWindow mode to mitigate a security 152 | * bug found in Chromium prior to version 83.0.4103.106. 153 | * See https://bugs.chromium.org/p/chromium/issues/detail?id=1083819 154 | * 155 | * Valid Urls set to open in new window will be routed back to load in the original WebView. 156 | * 157 | * @param view 158 | * @param isDialog 159 | * @param isUserGesture 160 | * @param resultMsg 161 | * @return 162 | */ 163 | @Override 164 | public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { 165 | WebView inAppWebView = view; 166 | final WebViewClient webViewClient = 167 | new WebViewClient() { 168 | @Override 169 | public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { 170 | inAppWebView.loadUrl(request.getUrl().toString()); 171 | return true; 172 | } 173 | 174 | @Override 175 | public boolean shouldOverrideUrlLoading(WebView view, String url) { 176 | inAppWebView.loadUrl(url); 177 | return true; 178 | } 179 | }; 180 | 181 | final WebView newWebView = new WebView(view.getContext()); 182 | newWebView.setWebViewClient(webViewClient); 183 | 184 | final WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; 185 | transport.setWebView(newWebView); 186 | resultMsg.sendToTarget(); 187 | 188 | return true; 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/android/res/drawable/ic_action_close.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /src/android/res/drawable/ic_action_more.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/android/res/drawable/ic_action_previous_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /src/browser/InAppBrowserProxy.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * 20 | */ 21 | 22 | const modulemapper = require('cordova/modulemapper'); 23 | 24 | let browserWrap, popup, navigationButtonsDiv, navigationButtonsDivInner, backButton, forwardButton, closeButton; 25 | 26 | function attachNavigationEvents (element, callback) { 27 | const onError = function () { 28 | try { 29 | callback({ type: 'loaderror', url: this.contentWindow.location.href }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal 30 | } catch (err) { 31 | // blocked by CORS :\ 32 | callback({ type: 'loaderror', url: null }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal 33 | } 34 | }; 35 | 36 | element.addEventListener('pageshow', function () { 37 | try { 38 | callback({ type: 'loadstart', url: this.contentWindow.location.href }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal 39 | } catch (err) { 40 | // blocked by CORS :\ 41 | callback({ type: 'loadstart', url: null }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal 42 | } 43 | }); 44 | 45 | element.addEventListener('load', function () { 46 | try { 47 | callback({ type: 'loadstop', url: this.contentWindow.location.href }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal 48 | } catch (err) { 49 | // blocked by CORS :\ 50 | callback({ type: 'loadstop', url: null }, { keepCallback: true }); // eslint-disable-line n/no-callback-literal 51 | } 52 | }); 53 | 54 | element.addEventListener('error', onError); 55 | element.addEventListener('abort', onError); 56 | } 57 | 58 | const IAB = { 59 | close: function (win, lose) { 60 | if (browserWrap) { 61 | // use the "open" function callback so that the exit event is fired properly 62 | if (IAB._win) IAB._win({ type: 'exit' }); 63 | 64 | browserWrap.parentNode.removeChild(browserWrap); 65 | browserWrap = null; 66 | popup = null; 67 | } 68 | }, 69 | 70 | show: function (win, lose) { 71 | if (browserWrap) { 72 | browserWrap.style.display = 'block'; 73 | } 74 | }, 75 | 76 | open: function (win, lose, args) { 77 | const strUrl = args[0]; 78 | const target = args[1]; 79 | const features = args[2]; 80 | 81 | IAB._win = win; 82 | 83 | if (target === '_self' || !target) { 84 | window.location = strUrl; 85 | } else if (target === '_system') { 86 | modulemapper.getOriginalSymbol(window, 'window.open').call(window, strUrl, '_blank'); 87 | } else { 88 | // "_blank" or anything else 89 | if (!browserWrap) { 90 | browserWrap = document.createElement('div'); 91 | browserWrap.style.position = 'absolute'; 92 | browserWrap.style.top = '0'; 93 | browserWrap.style.left = '0'; 94 | browserWrap.style.boxSizing = 'border-box'; 95 | browserWrap.style.borderWidth = '40px'; 96 | browserWrap.style.width = '100vw'; 97 | browserWrap.style.height = '100vh'; 98 | browserWrap.style.borderStyle = 'solid'; 99 | browserWrap.style.borderColor = 'rgba(0,0,0,0.25)'; 100 | 101 | browserWrap.onclick = function () { 102 | setTimeout(function () { 103 | IAB.close(); 104 | }, 0); 105 | }; 106 | 107 | document.body.appendChild(browserWrap); 108 | } 109 | 110 | if (features.indexOf('hidden=yes') !== -1) { 111 | browserWrap.style.display = 'none'; 112 | } 113 | 114 | popup = document.createElement('iframe'); 115 | popup.style.borderWidth = '0px'; 116 | popup.style.width = '100%'; 117 | 118 | browserWrap.appendChild(popup); 119 | 120 | if (features.indexOf('location=yes') !== -1 || features.indexOf('location') === -1) { 121 | popup.style.height = 'calc(100% - 60px)'; 122 | popup.style.marginBottom = '-4px'; 123 | 124 | navigationButtonsDiv = document.createElement('div'); 125 | navigationButtonsDiv.style.height = '60px'; 126 | navigationButtonsDiv.style.backgroundColor = '#404040'; 127 | navigationButtonsDiv.style.zIndex = '999'; 128 | navigationButtonsDiv.onclick = function (e) { 129 | e.cancelBubble = true; 130 | }; 131 | 132 | navigationButtonsDivInner = document.createElement('div'); 133 | navigationButtonsDivInner.style.paddingTop = '10px'; 134 | navigationButtonsDivInner.style.height = '50px'; 135 | navigationButtonsDivInner.style.width = '160px'; 136 | navigationButtonsDivInner.style.margin = '0 auto'; 137 | navigationButtonsDivInner.style.backgroundColor = '#404040'; 138 | navigationButtonsDivInner.style.zIndex = '999'; 139 | navigationButtonsDivInner.onclick = function (e) { 140 | e.cancelBubble = true; 141 | }; 142 | 143 | backButton = document.createElement('button'); 144 | backButton.style.width = '40px'; 145 | backButton.style.height = '40px'; 146 | backButton.style.borderRadius = '40px'; 147 | 148 | backButton.innerHTML = '←'; 149 | backButton.addEventListener('click', function (e) { 150 | if (popup.canGoBack) { 151 | popup.goBack(); 152 | } 153 | }); 154 | 155 | forwardButton = document.createElement('button'); 156 | forwardButton.style.marginLeft = '20px'; 157 | forwardButton.style.width = '40px'; 158 | forwardButton.style.height = '40px'; 159 | forwardButton.style.borderRadius = '40px'; 160 | 161 | forwardButton.innerHTML = '→'; 162 | forwardButton.addEventListener('click', function (e) { 163 | if (popup.canGoForward) { 164 | popup.goForward(); 165 | } 166 | }); 167 | 168 | closeButton = document.createElement('button'); 169 | closeButton.style.marginLeft = '20px'; 170 | closeButton.style.width = '40px'; 171 | closeButton.style.height = '40px'; 172 | closeButton.style.borderRadius = '40px'; 173 | 174 | closeButton.innerHTML = '✖'; 175 | closeButton.addEventListener('click', function (e) { 176 | setTimeout(function () { 177 | IAB.close(); 178 | }, 0); 179 | }); 180 | 181 | // iframe navigation is not yet supported 182 | backButton.disabled = true; 183 | forwardButton.disabled = true; 184 | 185 | navigationButtonsDivInner.appendChild(backButton); 186 | navigationButtonsDivInner.appendChild(forwardButton); 187 | navigationButtonsDivInner.appendChild(closeButton); 188 | navigationButtonsDiv.appendChild(navigationButtonsDivInner); 189 | 190 | browserWrap.appendChild(navigationButtonsDiv); 191 | } else { 192 | popup.style.height = '100%'; 193 | } 194 | 195 | // start listening for navigation events 196 | attachNavigationEvents(popup, win); 197 | 198 | popup.src = strUrl; 199 | } 200 | }, 201 | 202 | injectScriptCode: function (win, fail, args) { 203 | const code = args[0]; 204 | const hasCallback = args[1]; 205 | 206 | if (browserWrap && popup) { 207 | try { 208 | popup.contentWindow.eval(code); 209 | if (hasCallback) { 210 | win([]); 211 | } 212 | } catch (e) { 213 | console.error('Error occured while trying to injectScriptCode: ' + JSON.stringify(e)); 214 | } 215 | } 216 | }, 217 | 218 | injectScriptFile: function (win, fail, args) { 219 | const msg = 'Browser cordova-plugin-inappbrowser injectScriptFile is not yet implemented'; 220 | console.warn(msg); 221 | if (fail) { 222 | fail(msg); 223 | } 224 | }, 225 | 226 | injectStyleCode: function (win, fail, args) { 227 | const msg = 'Browser cordova-plugin-inappbrowser injectStyleCode is not yet implemented'; 228 | console.warn(msg); 229 | if (fail) { 230 | fail(msg); 231 | } 232 | }, 233 | 234 | injectStyleFile: function (win, fail, args) { 235 | const msg = 'Browser cordova-plugin-inappbrowser injectStyleFile is not yet implemented'; 236 | console.warn(msg); 237 | if (fail) { 238 | fail(msg); 239 | } 240 | } 241 | }; 242 | 243 | module.exports = IAB; 244 | 245 | require('cordova/exec/proxy').add('InAppBrowser', module.exports); 246 | -------------------------------------------------------------------------------- /src/ios/CDVInAppBrowserNavigationController.h: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | #import 21 | #import 22 | 23 | 24 | @interface CDVInAppBrowserNavigationController : UINavigationController 25 | 26 | @property (nonatomic, weak) id orientationDelegate; 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /src/ios/CDVInAppBrowserNavigationController.m: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | #import "CDVInAppBrowserNavigationController.h" 21 | 22 | @implementation CDVInAppBrowserNavigationController : UINavigationController 23 | 24 | - (void) dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion { 25 | if ( self.presentedViewController) { 26 | [super dismissViewControllerAnimated:flag completion:completion]; 27 | } 28 | } 29 | 30 | - (void) viewDidLoad { 31 | [super viewDidLoad]; 32 | } 33 | 34 | - (CGRect) invertFrameIfNeeded:(CGRect)rect { 35 | if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) { 36 | CGFloat temp = rect.size.width; 37 | rect.size.width = rect.size.height; 38 | rect.size.height = temp; 39 | } 40 | rect.origin = CGPointZero; 41 | return rect; 42 | } 43 | 44 | #pragma mark CDVScreenOrientationDelegate 45 | 46 | - (BOOL)shouldAutorotate 47 | { 48 | if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(shouldAutorotate)]) { 49 | return [self.orientationDelegate shouldAutorotate]; 50 | } 51 | return YES; 52 | } 53 | 54 | - (UIInterfaceOrientationMask)supportedInterfaceOrientations 55 | { 56 | if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(supportedInterfaceOrientations)]) { 57 | return [self.orientationDelegate supportedInterfaceOrientations]; 58 | } 59 | 60 | return 1 << UIInterfaceOrientationPortrait; 61 | } 62 | 63 | @end 64 | -------------------------------------------------------------------------------- /src/ios/CDVInAppBrowserOptions.h: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | #import 21 | 22 | @interface CDVInAppBrowserOptions : NSObject {} 23 | 24 | @property (nonatomic, assign) BOOL location; 25 | @property (nonatomic, assign) BOOL toolbar; 26 | @property (nonatomic, copy) NSString* closebuttoncaption; 27 | @property (nonatomic, copy) NSString* backbuttoncaption; 28 | @property (nonatomic, copy) NSString* reloadcaption; 29 | @property (nonatomic, copy) NSString* openinbrowsercaption; 30 | @property (nonatomic, copy) NSString* copyurlcaption; 31 | @property (nonatomic, copy) NSString* sharecaption; 32 | @property (nonatomic, assign) BOOL lefttoright; 33 | @property (nonatomic, copy) NSString* toolbarposition; 34 | @property (nonatomic, assign) BOOL toolbartranslucent; 35 | @property (nonatomic, assign) BOOL cleardata; 36 | @property (nonatomic, assign) BOOL clearcache; 37 | @property (nonatomic, assign) BOOL clearsessioncache; 38 | @property (nonatomic, assign) BOOL hidespinner; 39 | 40 | @property (nonatomic, copy) NSString* presentationstyle; 41 | @property (nonatomic, copy) NSString* transitionstyle; 42 | 43 | @property (nonatomic, copy) NSString* title; 44 | @property (nonatomic, copy) NSString* subtitle; 45 | @property (nonatomic, copy) NSString* shareurl; 46 | @property (nonatomic, copy) NSString* theme; 47 | 48 | @property (nonatomic, assign) BOOL enableviewportscale; 49 | @property (nonatomic, assign) BOOL mediaplaybackrequiresuseraction; 50 | @property (nonatomic, assign) BOOL allowinlinemediaplayback; 51 | @property (nonatomic, assign) BOOL hidden; 52 | @property (nonatomic, assign) BOOL disallowoverscroll; 53 | @property (nonatomic, copy) NSString* beforeload; 54 | 55 | + (CDVInAppBrowserOptions*)parseOptions:(NSString*)options; 56 | 57 | @end 58 | -------------------------------------------------------------------------------- /src/ios/CDVInAppBrowserOptions.m: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | #import "CDVInAppBrowserOptions.h" 21 | 22 | @implementation CDVInAppBrowserOptions 23 | 24 | - (id)init 25 | { 26 | if (self = [super init]) { 27 | // default values 28 | self.location = YES; 29 | self.toolbar = YES; 30 | self.closebuttoncaption = nil; 31 | self.toolbarposition = @"bottom"; 32 | self.cleardata = NO; 33 | self.clearcache = NO; 34 | self.clearsessioncache = NO; 35 | self.hidespinner = NO; 36 | 37 | self.enableviewportscale = NO; 38 | self.mediaplaybackrequiresuseraction = NO; 39 | self.allowinlinemediaplayback = NO; 40 | self.hidden = NO; 41 | self.disallowoverscroll = NO; 42 | self.lefttoright = false; 43 | self.toolbartranslucent = YES; 44 | self.beforeload = @""; 45 | } 46 | 47 | return self; 48 | } 49 | 50 | + (CDVInAppBrowserOptions*)parseOptions:(NSString*)options 51 | { 52 | CDVInAppBrowserOptions* obj = [[CDVInAppBrowserOptions alloc] init]; 53 | 54 | // NOTE: this parsing does not handle quotes within values 55 | NSArray* pairs = [options componentsSeparatedByString:@","]; 56 | 57 | // parse keys and values, set the properties 58 | for (NSString* pair in pairs) { 59 | NSArray* keyvalue = [pair componentsSeparatedByString:@"="]; 60 | 61 | if ([keyvalue count] == 2) { 62 | NSString* key = [[keyvalue objectAtIndex:0] lowercaseString]; 63 | NSString* value = [keyvalue objectAtIndex:1]; 64 | NSString* value_lc = [value lowercaseString]; 65 | 66 | BOOL isBoolean = [value_lc isEqualToString:@"yes"] || [value_lc isEqualToString:@"no"]; 67 | NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init]; 68 | [numberFormatter setAllowsFloats:YES]; 69 | BOOL isNumber = [numberFormatter numberFromString:value_lc] != nil; 70 | 71 | // set the property according to the key name 72 | if ([obj respondsToSelector:NSSelectorFromString(key)]) { 73 | if (isNumber) { 74 | [obj setValue:[numberFormatter numberFromString:value_lc] forKey:key]; 75 | } else if (isBoolean) { 76 | [obj setValue:[NSNumber numberWithBool:[value_lc isEqualToString:@"yes"]] forKey:key]; 77 | } else { 78 | [obj setValue:value forKey:key]; 79 | } 80 | } 81 | } 82 | } 83 | 84 | return obj; 85 | } 86 | 87 | @end 88 | -------------------------------------------------------------------------------- /src/ios/CDVWKInAppBrowser.h: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | #import 21 | #import 22 | #import 23 | #import "CDVWKInAppBrowserUIDelegate.h" 24 | #import "CDVInAppBrowserOptions.h" 25 | #import "CDVInAppBrowserNavigationController.h" 26 | 27 | @class CDVWKInAppBrowserViewController; 28 | 29 | @interface CDVWKInAppBrowser : CDVPlugin { 30 | UIWindow * tmpWindow; 31 | 32 | @private 33 | NSString* _beforeload; 34 | BOOL _waitForBeforeload; 35 | } 36 | 37 | @property (nonatomic, retain) CDVWKInAppBrowser* instance; 38 | @property (nonatomic, retain) CDVInAppBrowserNavigationController* inAppBrowserNav; 39 | @property (nonatomic, retain) CDVWKInAppBrowserViewController* inAppBrowserViewController; 40 | @property (nonatomic, copy) NSString* callbackId; 41 | @property (nonatomic, copy) NSRegularExpression *callbackIdPattern; 42 | 43 | + (id) getInstance; 44 | - (void)open:(CDVInvokedUrlCommand*)command; 45 | - (void)close:(CDVInvokedUrlCommand*)command; 46 | - (void)injectScriptCode:(CDVInvokedUrlCommand*)command; 47 | - (void)show:(CDVInvokedUrlCommand*)command; 48 | - (void)hide:(CDVInvokedUrlCommand*)command; 49 | - (void)loadAfterBeforeload:(CDVInvokedUrlCommand*)command; 50 | 51 | @end 52 | 53 | @interface CDVWKInAppBrowserViewController : UIViewController { 54 | @private 55 | CDVInAppBrowserOptions *_browserOptions; 56 | NSDictionary *_settings; 57 | } 58 | 59 | @property (nonatomic, strong) IBOutlet WKWebView* webView; 60 | @property (nonatomic, strong) IBOutlet WKWebViewConfiguration* configuration; 61 | @property (nonatomic, strong) IBOutlet UIBarButtonItem* closeBarButton; 62 | @property (nonatomic, strong) IBOutlet UIButton* closeInnerButton; 63 | @property (nonatomic, strong) IBOutlet UIBarButtonItem* optionsButton; 64 | @property (nonatomic, strong) IBOutlet UIActivityIndicatorView* spinner; 65 | @property (nonatomic, strong) IBOutlet UILabel* titleLabel; 66 | @property (nonatomic, strong) IBOutlet UILabel* subtitleLabel; 67 | @property (nonatomic, strong) IBOutlet CDVWKInAppBrowserUIDelegate* webViewUIDelegate; 68 | 69 | @property (nonatomic, weak) id orientationDelegate; 70 | @property (nonatomic, weak) CDVWKInAppBrowser* navigationDelegate; 71 | @property (nonatomic) NSURL* currentURL; 72 | @property (nonatomic) BOOL loadedOnce; 73 | 74 | - (void)forceClose; 75 | - (void)navigateTo:(NSURL*)url preloadCode:(NSString *)preloadCode; 76 | - (void)updateNavigationButtons; 77 | 78 | - (id)initWithBrowserOptions: (CDVInAppBrowserOptions*) browserOptions andSettings:(NSDictionary*) settings; 79 | 80 | @end 81 | -------------------------------------------------------------------------------- /src/ios/CDVWKInAppBrowserUIDelegate.h: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | #import 21 | 22 | @interface CDVWKInAppBrowserUIDelegate : NSObject { 23 | @private 24 | UIViewController* _viewController; 25 | } 26 | 27 | @property (nonatomic, copy) NSString* title; 28 | 29 | - (instancetype)initWithTitle:(NSString*)title; 30 | -(void) setViewController:(UIViewController*) viewController; 31 | 32 | @end 33 | -------------------------------------------------------------------------------- /src/ios/CDVWKInAppBrowserUIDelegate.m: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | #import "CDVWKInAppBrowserUIDelegate.h" 21 | 22 | @implementation CDVWKInAppBrowserUIDelegate 23 | 24 | - (instancetype)initWithTitle:(NSString*)title 25 | { 26 | self = [super init]; 27 | if (self) { 28 | self.title = title; 29 | } 30 | 31 | return self; 32 | } 33 | 34 | - (void) webView:(WKWebView*)webView runJavaScriptAlertPanelWithMessage:(NSString*)message 35 | initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void (^)(void))completionHandler 36 | { 37 | UIAlertController* alert = [UIAlertController alertControllerWithTitle:self.title 38 | message:message 39 | preferredStyle:UIAlertControllerStyleAlert]; 40 | 41 | UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK") 42 | style:UIAlertActionStyleDefault 43 | handler:^(UIAlertAction* action) 44 | { 45 | completionHandler(); 46 | [alert dismissViewControllerAnimated:YES completion:nil]; 47 | }]; 48 | 49 | [alert addAction:ok]; 50 | 51 | [[self getViewController] presentViewController:alert animated:YES completion:nil]; 52 | } 53 | 54 | - (void) webView:(WKWebView*)webView runJavaScriptConfirmPanelWithMessage:(NSString*)message 55 | initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void (^)(BOOL result))completionHandler 56 | { 57 | UIAlertController* alert = [UIAlertController alertControllerWithTitle:self.title 58 | message:message 59 | preferredStyle:UIAlertControllerStyleAlert]; 60 | 61 | UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK") 62 | style:UIAlertActionStyleDefault 63 | handler:^(UIAlertAction* action) 64 | { 65 | completionHandler(YES); 66 | [alert dismissViewControllerAnimated:YES completion:nil]; 67 | }]; 68 | 69 | [alert addAction:ok]; 70 | 71 | UIAlertAction* cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel") 72 | style:UIAlertActionStyleDefault 73 | handler:^(UIAlertAction* action) 74 | { 75 | completionHandler(NO); 76 | [alert dismissViewControllerAnimated:YES completion:nil]; 77 | }]; 78 | [alert addAction:cancel]; 79 | 80 | [[self getViewController] presentViewController:alert animated:YES completion:nil]; 81 | } 82 | 83 | - (void) webView:(WKWebView*)webView runJavaScriptTextInputPanelWithPrompt:(NSString*)prompt 84 | defaultText:(NSString*)defaultText initiatedByFrame:(WKFrameInfo*)frame 85 | completionHandler:(void (^)(NSString* result))completionHandler 86 | { 87 | UIAlertController* alert = [UIAlertController alertControllerWithTitle:self.title 88 | message:prompt 89 | preferredStyle:UIAlertControllerStyleAlert]; 90 | 91 | UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK") 92 | style:UIAlertActionStyleDefault 93 | handler:^(UIAlertAction* action) 94 | { 95 | completionHandler(((UITextField*)alert.textFields[0]).text); 96 | [alert dismissViewControllerAnimated:YES completion:nil]; 97 | }]; 98 | 99 | [alert addAction:ok]; 100 | 101 | UIAlertAction* cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel") 102 | style:UIAlertActionStyleDefault 103 | handler:^(UIAlertAction* action) 104 | { 105 | completionHandler(nil); 106 | [alert dismissViewControllerAnimated:YES completion:nil]; 107 | }]; 108 | [alert addAction:cancel]; 109 | 110 | [alert addTextFieldWithConfigurationHandler:^(UITextField* textField) { 111 | textField.text = defaultText; 112 | }]; 113 | 114 | [[self getViewController] presentViewController:alert animated:YES completion:nil]; 115 | } 116 | 117 | -(UIViewController*) getViewController 118 | { 119 | return _viewController; 120 | } 121 | 122 | -(void) setViewController:(UIViewController*) viewController 123 | { 124 | _viewController = viewController; 125 | } 126 | 127 | @end 128 | -------------------------------------------------------------------------------- /tests/.eslintrc.yml: -------------------------------------------------------------------------------- 1 | env: 2 | jasmine: true -------------------------------------------------------------------------------- /tests/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cordova-plugin-inappbrowser-tests", 3 | "version": "6.0.1-dev", 4 | "description": "", 5 | "cordova": { 6 | "id": "cordova-plugin-inappbrowser-tests", 7 | "platforms": [] 8 | }, 9 | "keywords": [ 10 | "ecosystem:cordova" 11 | ], 12 | "author": "", 13 | "license": "Apache-2.0" 14 | } 15 | -------------------------------------------------------------------------------- /tests/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | 20 | 21 | 24 | Cordova InAppBrowser Plugin Tests 25 | Apache 2.0 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /tests/resources/inject.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | #style-update-file { 20 | display: block !important; 21 | } 22 | -------------------------------------------------------------------------------- /tests/resources/inject.html: -------------------------------------------------------------------------------- 1 | 2 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | Cordova Mobile Spec 29 | 30 | 31 | 32 |

InAppBrowser - Script / Style Injection Test

33 | 34 | 35 |
User-Agent:
36 | 37 | 44 | 45 | -------------------------------------------------------------------------------- /tests/resources/inject.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | const d = document.getElementById('header'); 21 | d.innerHTML = 'Script file successfully injected'; 22 | -------------------------------------------------------------------------------- /tests/resources/local.html: -------------------------------------------------------------------------------- 1 | 2 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | IAB test page 29 | 30 | 36 | 39 | 40 | 41 |

Local URL

42 |
43 | You have successfully loaded a local URL: 44 | 45 |
46 |
47 |
User-Agent =
48 |
49 |
Likely running inAppBrowser: Device version from Cordova=not found, Back link should not work, toolbar may be present, logcat should show failed 'gap:' calls.
50 |
51 |
Visit Google (whitelisted)
52 |
Visit Yahoo (not whitelisted)
53 | 54 | 55 |

Back 56 |

57 | 58 |

tall div with border
59 | 60 | 67 | 68 | -------------------------------------------------------------------------------- /tests/resources/local.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mytonwalletorg/cordova-plugin-inappbrowser/9e0abc2d9fc79b1031ca941259e70b25395bc8a3/tests/resources/local.pdf -------------------------------------------------------------------------------- /tests/resources/video.html: -------------------------------------------------------------------------------- 1 | 2 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | Cordova Mobile Spec 29 | 30 | 31 | 32 | 37 |
38 | 39 | 40 |
41 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /tests/tests.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * 20 | */ 21 | 22 | const cordova = require('cordova'); 23 | const isIos = cordova.platformId === 'ios'; 24 | const isAndroid = cordova.platformId === 'android'; 25 | const isBrowser = cordova.platformId === 'browser'; 26 | 27 | window.alert = window.alert || navigator.notification.alert; 28 | 29 | exports.defineAutoTests = function () { 30 | const createTests = function (platformOpts) { 31 | platformOpts = platformOpts || ''; 32 | 33 | describe('cordova.InAppBrowser', function () { 34 | it('inappbrowser.spec.1 should exist', function () { 35 | expect(cordova.InAppBrowser).toBeDefined(); 36 | }); 37 | 38 | it('inappbrowser.spec.2 should contain open function', function () { 39 | expect(cordova.InAppBrowser.open).toBeDefined(); 40 | expect(cordova.InAppBrowser.open).toEqual(jasmine.any(Function)); 41 | }); 42 | }); 43 | 44 | describe('open method', function () { 45 | if (cordova.platformId === 'osx') { 46 | pending('Open method not fully supported on OSX.'); 47 | return; 48 | } 49 | 50 | let iabInstance; 51 | let originalTimeout; 52 | const url = 'https://dist.apache.org/repos/dist/dev/cordova/'; 53 | const badUrl = 'http://bad-uri/'; 54 | 55 | beforeEach(function () { 56 | // increase timeout to ensure test url could be loaded within test time 57 | originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; 58 | jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; 59 | 60 | iabInstance = null; 61 | }); 62 | 63 | afterEach(function (done) { 64 | // restore original timeout 65 | jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; 66 | 67 | if (iabInstance !== null && iabInstance.close) { 68 | iabInstance.close(); 69 | } 70 | iabInstance = null; 71 | // add some extra time so that iab dialog is closed 72 | setTimeout(done, 2000); 73 | }); 74 | 75 | function verifyEvent (evt, type) { 76 | expect(evt).toBeDefined(); 77 | expect(evt.type).toEqual(type); 78 | // `exit` event does not have url field, browser returns null url for CORS requests 79 | if (type !== 'exit' && !isBrowser) { 80 | expect(evt.url).toEqual(url); 81 | } 82 | } 83 | 84 | function verifyLoadErrorEvent (evt) { 85 | expect(evt).toBeDefined(); 86 | expect(evt.type).toEqual('loaderror'); 87 | expect(evt.url).toEqual(badUrl); 88 | expect(evt.code).toEqual(jasmine.any(Number)); 89 | expect(evt.message).toEqual(jasmine.any(String)); 90 | } 91 | 92 | it('inappbrowser.spec.3 should return InAppBrowser instance with required methods', function () { 93 | iabInstance = cordova.InAppBrowser.open(url, '_blank', platformOpts); 94 | 95 | expect(iabInstance).toBeDefined(); 96 | 97 | expect(iabInstance.addEventListener).toEqual(jasmine.any(Function)); 98 | expect(iabInstance.removeEventListener).toEqual(jasmine.any(Function)); 99 | expect(iabInstance.close).toEqual(jasmine.any(Function)); 100 | expect(iabInstance.show).toEqual(jasmine.any(Function)); 101 | expect(iabInstance.hide).toEqual(jasmine.any(Function)); 102 | expect(iabInstance.executeScript).toEqual(jasmine.any(Function)); 103 | expect(iabInstance.insertCSS).toEqual(jasmine.any(Function)); 104 | }); 105 | 106 | it('inappbrowser.spec.4 should support loadstart and loadstop events', function (done) { 107 | const onLoadStart = jasmine.createSpy('loadstart event callback').and.callFake(function (evt) { 108 | verifyEvent(evt, 'loadstart'); 109 | }); 110 | 111 | iabInstance = cordova.InAppBrowser.open(url, '_blank', platformOpts); 112 | iabInstance.addEventListener('loadstart', onLoadStart); 113 | iabInstance.addEventListener('loadstop', function (evt) { 114 | verifyEvent(evt, 'loadstop'); 115 | if (!isBrowser) { 116 | // according to documentation, "loadstart" event is not supported on browser 117 | // https://github.com/apache/cordova-plugin-inappbrowser#browser-quirks-1 118 | expect(onLoadStart).toHaveBeenCalled(); 119 | } 120 | done(); 121 | }); 122 | }); 123 | 124 | it('inappbrowser.spec.5 should support exit event', function (done) { 125 | iabInstance = cordova.InAppBrowser.open(url, '_blank', platformOpts); 126 | iabInstance.addEventListener('exit', function (evt) { 127 | verifyEvent(evt, 'exit'); 128 | done(); 129 | }); 130 | iabInstance.addEventListener('loadstop', function (evt) { 131 | iabInstance.close(); 132 | iabInstance = null; 133 | }); 134 | }); 135 | 136 | it('inappbrowser.spec.6 should support loaderror event', function (done) { 137 | if (isBrowser) { 138 | // according to documentation, "loaderror" event is not supported on browser 139 | // https://github.com/apache/cordova-plugin-inappbrowser#browser-quirks-1 140 | pending("Browser platform doesn't support loaderror event"); 141 | } 142 | iabInstance = cordova.InAppBrowser.open(badUrl, '_blank', platformOpts); 143 | iabInstance.addEventListener('loaderror', function (evt) { 144 | verifyLoadErrorEvent(evt); 145 | done(); 146 | }); 147 | }); 148 | 149 | it('inappbrowser.spec.7 should support message event', function (done) { 150 | if (!isAndroid && !isIos) { 151 | return pending(cordova.platformId + " platform doesn't support message event"); 152 | } 153 | const messageKey = 'my_message'; 154 | const messageValue = 'is_this'; 155 | iabInstance = cordova.InAppBrowser.open(url, '_blank', platformOpts); 156 | iabInstance.addEventListener('message', function (evt) { 157 | // Verify message event 158 | expect(evt).toBeDefined(); 159 | expect(evt.type).toEqual('message'); 160 | expect(evt.data).toBeDefined(); 161 | expect(evt.data[messageKey]).toBeDefined(); 162 | expect(evt.data[messageKey]).toEqual(messageValue); 163 | done(); 164 | }); 165 | iabInstance.addEventListener('loadstop', function (evt) { 166 | const code = 167 | '(function(){\n' + 168 | ' var message = {' + 169 | messageKey + 170 | ': "' + 171 | messageValue + 172 | '"};\n' + 173 | ' webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(message));\n' + 174 | '})()'; 175 | iabInstance.executeScript({ code }); 176 | }); 177 | }); 178 | }); 179 | }; 180 | createTests(); 181 | }; 182 | 183 | exports.defineManualTests = function (contentEl, createActionButton) { 184 | const platformOpts = ''; 185 | const platform_info = ''; 186 | 187 | function doOpen (url, target, params, numExpectedRedirects, useWindowOpen) { 188 | numExpectedRedirects = numExpectedRedirects || 0; 189 | useWindowOpen = useWindowOpen || false; 190 | console.log('Opening ' + url); 191 | 192 | let counts; 193 | let lastLoadStartURL; 194 | let wasReset = false; 195 | function reset () { 196 | counts = { 197 | loaderror: 0, 198 | loadstart: 0, 199 | loadstop: 0, 200 | exit: 0 201 | }; 202 | lastLoadStartURL = ''; 203 | } 204 | reset(); 205 | 206 | let iab; 207 | const callbacks = { 208 | loaderror: logEvent, 209 | loadstart: logEvent, 210 | loadstop: logEvent, 211 | exit: logEvent 212 | }; 213 | if (useWindowOpen) { 214 | console.log('Use window.open() for url'); 215 | iab = window.open(url, target, params, callbacks); 216 | } else { 217 | if (platformOpts) { 218 | params += (params ? ',' : '') + platformOpts; 219 | } 220 | iab = cordova.InAppBrowser.open(url, target, params, callbacks); 221 | } 222 | if (!iab) { 223 | alert('open returned ' + iab); // eslint-disable-line no-undef 224 | return; 225 | } 226 | 227 | function logEvent (e) { 228 | console.log('IAB event=' + JSON.stringify(e)); 229 | counts[e.type]++; 230 | // Verify that event.url gets updated on redirects. 231 | if (e.type === 'loadstart') { 232 | if (e.url === lastLoadStartURL) { 233 | alert('Unexpected: loadstart fired multiple times for the same URL.'); // eslint-disable-line no-undef 234 | } 235 | lastLoadStartURL = e.url; 236 | } 237 | // Verify the right number of loadstart events were fired. 238 | if (e.type === 'loadstop' || e.type === 'loaderror') { 239 | if (e.url !== lastLoadStartURL) { 240 | alert('Unexpected: ' + e.type + " event.url != loadstart's event.url"); // eslint-disable-line no-undef 241 | } 242 | if (numExpectedRedirects === 0 && counts.loadstart !== 1) { 243 | // Do allow a loaderror without a loadstart (e.g. in the case of an invalid URL). 244 | if (!(e.type === 'loaderror' && counts.loadstart === 0)) { 245 | alert('Unexpected: got multiple loadstart events. (' + counts.loadstart + ')'); // eslint-disable-line no-undef 246 | } 247 | } else if (numExpectedRedirects > 0 && counts.loadstart < numExpectedRedirects + 1) { 248 | alert( 249 | 'Unexpected: should have got at least ' + 250 | (numExpectedRedirects + 1) + 251 | ' loadstart events, but got ' + 252 | counts.loadstart 253 | ); // eslint-disable-line no-undef 254 | } 255 | wasReset = true; 256 | numExpectedRedirects = 0; 257 | reset(); 258 | } 259 | // Verify that loadend / loaderror was called. 260 | if (e.type === 'exit') { 261 | const numStopEvents = counts.loadstop + counts.loaderror; 262 | if (numStopEvents === 0 && !wasReset) { 263 | alert('Unexpected: browser closed without a loadstop or loaderror.'); // eslint-disable-line no-undef 264 | } else if (numStopEvents > 1) { 265 | alert('Unexpected: got multiple loadstop/loaderror events.'); // eslint-disable-line no-undef 266 | } 267 | } 268 | } 269 | 270 | return iab; 271 | } 272 | 273 | function doHookOpen (url, target, params, numExpectedRedirects) { 274 | const originalFunc = window.open; 275 | const wasClobbered = Object.prototype.hasOwnProperty.call(window, 'open'); 276 | window.open = cordova.InAppBrowser.open; 277 | 278 | try { 279 | doOpen(url, target, params, numExpectedRedirects, true); 280 | } finally { 281 | if (wasClobbered) { 282 | window.open = originalFunc; 283 | } else { 284 | console.log('just delete, to restore open from prototype'); 285 | delete window.open; 286 | } 287 | } 288 | } 289 | 290 | function openWithStyle (url, cssUrl, useCallback) { 291 | const iab = doOpen(url, '_blank', 'location=yes'); 292 | const callback = function (results) { 293 | if (results && results.length === 0) { 294 | alert('Results verified'); // eslint-disable-line no-undef 295 | } else { 296 | console.log(results); 297 | alert('Got: ' + typeof results + '\n' + JSON.stringify(results)); // eslint-disable-line no-undef 298 | } 299 | }; 300 | if (cssUrl) { 301 | iab.addEventListener('loadstop', function (event) { 302 | iab.insertCSS({ file: cssUrl }, useCallback && callback); 303 | }); 304 | } else { 305 | iab.addEventListener('loadstop', function (event) { 306 | iab.insertCSS({ code: '#style-update-literal { \ndisplay: block !important; \n}' }, useCallback && callback); 307 | }); 308 | } 309 | } 310 | 311 | function openWithScript (url, jsUrl, useCallback) { 312 | const iab = doOpen(url, '_blank', 'location=yes'); 313 | if (jsUrl) { 314 | iab.addEventListener('loadstop', function (event) { 315 | iab.executeScript( 316 | { file: jsUrl }, 317 | useCallback && 318 | function (results) { 319 | if (results && results.length === 0) { 320 | alert('Results verified'); // eslint-disable-line no-undef 321 | } else { 322 | console.log(results); 323 | alert('Got: ' + typeof results + '\n' + JSON.stringify(results)); // eslint-disable-line no-undef 324 | } 325 | } 326 | ); 327 | }); 328 | } else { 329 | iab.addEventListener('loadstop', function (event) { 330 | const code = 331 | '(function(){\n' + 332 | ' var header = document.getElementById("header");\n' + 333 | ' header.innerHTML = "Script literal successfully injected";\n' + 334 | ' return "abc";\n' + 335 | '})()'; 336 | iab.executeScript( 337 | { code }, 338 | useCallback && 339 | function (results) { 340 | if (results && results.length === 1 && results[0] === 'abc') { 341 | alert('Results verified'); // eslint-disable-line no-undef 342 | } else { 343 | console.log(results); 344 | alert('Got: ' + typeof results + '\n' + JSON.stringify(results)); // eslint-disable-line no-undef 345 | } 346 | } 347 | ); 348 | }); 349 | } 350 | } 351 | let hiddenwnd = null; 352 | const loadlistener = function (event) { 353 | alert('background window loaded '); 354 | }; // eslint-disable-line no-undef 355 | function openHidden (url, startHidden) { 356 | let shopt = startHidden ? 'hidden=yes' : ''; 357 | if (platformOpts) { 358 | shopt += (shopt ? ',' : '') + platformOpts; 359 | } 360 | hiddenwnd = cordova.InAppBrowser.open(url, 'random_string', shopt); 361 | if (!hiddenwnd) { 362 | alert('cordova.InAppBrowser.open returned ' + hiddenwnd); // eslint-disable-line no-undef 363 | return; 364 | } 365 | if (startHidden) hiddenwnd.addEventListener('loadstop', loadlistener); 366 | } 367 | function showHidden () { 368 | if (hiddenwnd) { 369 | hiddenwnd.show(); 370 | } 371 | } 372 | function closeHidden () { 373 | if (hiddenwnd) { 374 | hiddenwnd.removeEventListener('loadstop', loadlistener); 375 | hiddenwnd.close(); 376 | hiddenwnd = null; 377 | } 378 | } 379 | 380 | const info_div = 381 | '

InAppBrowser

' + 382 | '
' + 383 | 'Make sure http://cordova.apache.org and http://google.co.uk and https://www.google.co.uk are white listed.
' + 384 | 'Make sure http://www.apple.com is not in the white list.
' + 385 | 'In iOS, starred * tests will put the app in a state with no way to return.
' + 386 | '

User-Agent: ' + 387 | '

'; 388 | 389 | const local_tests = 390 | '

Local URL

' + 391 | '
' + 392 | 'Expected result: opens successfully in CordovaWebView.' + 393 | '

' + 394 | 'Expected result: opens successfully in CordovaWebView (using hook of window.open()).' + 395 | '

' + 396 | 'Expected result: opens successfully in CordovaWebView.' + 397 | '

' + 398 | 'Expected result: fails to open' + 399 | '

' + 400 | 'Expected result: opens successfully in InAppBrowser with locationBar at top.' + 401 | '

' + 402 | 'Expected result: opens successfully in InAppBrowser without locationBar.' + 403 | '

' + 404 | 'Expected result: opens successfully in InAppBrowser with locationBar. On iOS the toolbar is at the bottom.' + 405 | '

' + 406 | 'Expected result: opens successfully in InAppBrowser with locationBar. On iOS the toolbar is at the top.' + 407 | '

' + 408 | 'Expected result: open successfully in InAppBrowser with no locationBar. On iOS the toolbar is at the top.'; 409 | 410 | const white_listed_tests = 411 | '

White Listed URL

' + 412 | '
' + 413 | 'Expected result: open successfully in CordovaWebView to cordova.apache.org' + 414 | '

' + 415 | 'Expected result: open successfully in CordovaWebView to cordova.apache.org (using hook of window.open())' + 416 | '

' + 417 | 'Expected result: open successfully in CordovaWebView to cordova.apache.org' + 418 | '

' + 419 | 'Expected result: open successfully in system browser to cordova.apache.org' + 420 | '

' + 421 | 'Expected result: open successfully in InAppBrowser to cordova.apache.org' + 422 | '

' + 423 | 'Expected result: open successfully in InAppBrowser to cordova.apache.org' + 424 | '

' + 425 | 'Expected result: open successfully in InAppBrowser to cordova.apache.org with no location bar.'; 426 | 427 | const non_white_listed_tests = 428 | '

Non White Listed URL

' + 429 | '
' + 430 | 'Expected result: open successfully in InAppBrowser to apple.com.' + 431 | '

' + 432 | 'Expected result: open successfully in InAppBrowser to apple.com (using hook of window.open()).' + 433 | '

' + 434 | 'Expected result: open successfully in InAppBrowser to apple.com (_self enforces whitelist).' + 435 | '

' + 436 | 'Expected result: open successfully in system browser to apple.com.' + 437 | '

' + 438 | 'Expected result: open successfully in InAppBrowser to apple.com.' + 439 | '

' + 440 | 'Expected result: open successfully in InAppBrowser to apple.com.' + 441 | '

' + 442 | 'Expected result: open successfully in InAppBrowser to apple.com without locationBar.'; 443 | 444 | const page_with_redirects_tests = 445 | '

Page with redirect

' + 446 | '
' + 447 | 'Expected result: should 301 and open successfully in InAppBrowser to https://www.google.co.uk.' + 448 | '

' + 449 | 'Expected result: should 302 and open successfully in InAppBrowser to www.zhihu.com/answer/16714076.'; 450 | 451 | const pdf_url_tests = 452 | '

PDF URL

' + 453 | '
' + 454 | 'Expected result: InAppBrowser opens. PDF should render on iOS.' + 455 | '

' + 456 | 'Expected result: InAppBrowser opens. PDF should render on iOS.'; 457 | 458 | const invalid_url_tests = 459 | '

Invalid URL

' + 460 | '
' + 461 | 'Expected result: fail to load in InAppBrowser.' + 462 | '

' + 463 | 'Expected result: fail to load in InAppBrowser.' + 464 | '

' + 465 | 'Expected result: fail to load in InAppBrowser (404).'; 466 | 467 | const css_js_injection_tests = 468 | '

CSS / JS Injection

' + 469 | '
' + 470 | 'Expected result: open successfully in InAppBrowser without text "Style updated from..."' + 471 | '

' + 472 | 'Expected result: open successfully in InAppBrowser with "Style updated from file".' + 473 | '

' + 474 | 'Expected result: open successfully in InAppBrowser with "Style updated from file", and alert dialog with text "Results verified".' + 475 | '

' + 476 | 'Expected result: open successfully in InAppBrowser with "Style updated from literal".' + 477 | '

' + 478 | 'Expected result: open successfully in InAppBrowser with "Style updated from literal", and alert dialog with text "Results verified".' + 479 | '

' + 480 | 'Expected result: open successfully in InAppBrowser with text "Script file successfully injected".' + 481 | '

' + 482 | 'Expected result: open successfully in InAppBrowser with text "Script file successfully injected" and alert dialog with the text "Results verified".' + 483 | '

' + 484 | 'Expected result: open successfully in InAppBrowser with the text "Script literal successfully injected" .' + 485 | '

' + 486 | 'Expected result: open successfully in InAppBrowser with the text "Script literal successfully injected" and alert dialog with the text "Results verified".'; 487 | 488 | const open_hidden_tests = 489 | '

Open Hidden

' + 490 | '
' + 491 | 'Expected result: no additional browser window. Alert appears with the text "background window loaded".' + 492 | '

' + 493 | 'Expected result: after first clicking on previous test "create hidden", open successfully in InAppBrowser to https://www.google.co.uk.' + 494 | '

' + 495 | 'Expected result: no output. But click on "show hidden" again and nothing should be shown.' + 496 | '

' + 497 | 'Expected result: open successfully in InAppBrowser to https://www.google.co.uk' + 498 | '

' + 499 | 'Expected result: open successfully in InAppBrowser to https://www.google.co.uk. Hide after 2 seconds'; 500 | 501 | const clearing_cache_tests = 502 | '

Clearing Cache

' + 503 | '
' + 504 | 'Expected result: ?' + 505 | '

' + 506 | 'Expected result: ?'; 507 | 508 | const video_tag_tests = 509 | '

Video tag

' + 510 | '
' + 511 | 'Expected result: open successfully in InAppBrowser with an embedded video plays automatically on iOS and Android.' + 512 | '
' + 513 | 'Expected result: open successfully in InAppBrowser with an embedded video plays automatically on iOS and Android.' + 514 | '
' + 515 | 'Expected result: open successfully in InAppBrowser with an embedded video does not play automatically on iOS and Android but rather works after clicking the "play" button.'; 516 | 517 | const local_with_anchor_tag_tests = 518 | '

Local with anchor tag

' + 519 | '
' + 520 | 'Expected result: open successfully in InAppBrowser to the local page, scrolled to the top as normal.' + 521 | '

' + 522 | 'Expected result: open successfully in InAppBrowser to the local page, scrolled to the beginning of the tall div with border.'; 523 | 524 | const hardwareback_tests = 525 | '

HardwareBack

' + 526 | '

' + 527 | 'Expected result: By default hardwareback is yes so pressing back button should navigate backwards in history then close InAppBrowser' + 528 | '

' + 529 | 'Expected result: hardwareback=yes pressing back button should navigate backwards in history then close InAppBrowser' + 530 | '

' + 531 | 'Expected result: hardwareback=no pressing back button should close InAppBrowser regardless history' + 532 | '

' + 533 | 'Expected result: consistently open browsers with with the appropriate option: hardwareback=defaults to yes then hardwareback=no then hardwareback=defaults to yes. By default hardwareback is yes so pressing back button should navigate backwards in history then close InAppBrowser'; 534 | 535 | contentEl.innerHTML = 536 | info_div + 537 | platform_info + 538 | local_tests + 539 | white_listed_tests + 540 | non_white_listed_tests + 541 | page_with_redirects_tests + 542 | pdf_url_tests + 543 | invalid_url_tests + 544 | css_js_injection_tests + 545 | open_hidden_tests + 546 | clearing_cache_tests + 547 | video_tag_tests + 548 | local_with_anchor_tag_tests + 549 | hardwareback_tests; 550 | 551 | document.getElementById('user-agent').textContent = navigator.userAgent; 552 | 553 | // we are already in cdvtests directory 554 | const basePath = 'iab-resources/'; 555 | const localhtml = basePath + 'local.html'; 556 | const localpdf = basePath + 'local.pdf'; 557 | const injecthtml = basePath + 'inject.html'; 558 | const injectjs = 'inject.js'; 559 | const injectcss = 'inject.css'; 560 | const videohtml = basePath + 'video.html'; 561 | 562 | // Local 563 | createActionButton( 564 | 'target=Default', 565 | function () { 566 | doOpen(localhtml); 567 | }, 568 | 'openLocal' 569 | ); 570 | createActionButton( 571 | 'target=Default (window.open)', 572 | function () { 573 | doHookOpen(localhtml); 574 | }, 575 | 'openLocalHook' 576 | ); 577 | createActionButton( 578 | 'target=_self', 579 | function () { 580 | doOpen(localhtml, '_self'); 581 | }, 582 | 'openLocalSelf' 583 | ); 584 | createActionButton( 585 | 'target=_system', 586 | function () { 587 | doOpen(localhtml, '_system'); 588 | }, 589 | 'openLocalSystem' 590 | ); 591 | createActionButton( 592 | 'target=_blank', 593 | function () { 594 | doOpen(localhtml, '_blank'); 595 | }, 596 | 'openLocalBlank' 597 | ); 598 | createActionButton( 599 | 'target=Random, location=no, disallowoverscroll=yes', 600 | function () { 601 | doOpen(localhtml, 'random_string', 'location=no, disallowoverscroll=yes'); 602 | }, 603 | 'openLocalRandomNoLocation' 604 | ); 605 | createActionButton( 606 | 'target=Random, toolbarposition=bottom', 607 | function () { 608 | doOpen(localhtml, 'random_string', 'toolbarposition=bottom'); 609 | }, 610 | 'openLocalRandomToolBarBottom' 611 | ); 612 | createActionButton( 613 | 'target=Random, toolbarposition=top', 614 | function () { 615 | doOpen(localhtml, 'random_string', 'toolbarposition=top'); 616 | }, 617 | 'openLocalRandomToolBarTop' 618 | ); 619 | createActionButton( 620 | 'target=Random, toolbarposition=top, location=no', 621 | function () { 622 | doOpen(localhtml, 'random_string', 'toolbarposition=top,location=no'); 623 | }, 624 | 'openLocalRandomToolBarTopNoLocation' 625 | ); 626 | 627 | // White Listed 628 | createActionButton( 629 | '* target=Default', 630 | function () { 631 | doOpen('https://cordova.apache.org'); 632 | }, 633 | 'openWhiteListed' 634 | ); 635 | createActionButton( 636 | '* target=Default (window.open)', 637 | function () { 638 | doHookOpen('https://cordova.apache.org'); 639 | }, 640 | 'openWhiteListedHook' 641 | ); 642 | createActionButton( 643 | '* target=_self', 644 | function () { 645 | doOpen('https://cordova.apache.org', '_self'); 646 | }, 647 | 'openWhiteListedSelf' 648 | ); 649 | createActionButton( 650 | 'target=_system', 651 | function () { 652 | doOpen('https://cordova.apache.org', '_system'); 653 | }, 654 | 'openWhiteListedSystem' 655 | ); 656 | createActionButton( 657 | 'target=_blank', 658 | function () { 659 | doOpen('https://cordova.apache.org', '_blank'); 660 | }, 661 | 'openWhiteListedBlank' 662 | ); 663 | createActionButton( 664 | 'target=Random', 665 | function () { 666 | doOpen('https://cordova.apache.org', 'random_string'); 667 | }, 668 | 'openWhiteListedRandom' 669 | ); 670 | createActionButton( 671 | '* target=Random, no location bar', 672 | function () { 673 | doOpen('https://cordova.apache.org', 'random_string', 'location=no'); 674 | }, 675 | 'openWhiteListedRandomNoLocation' 676 | ); 677 | 678 | // Non White Listed 679 | createActionButton( 680 | 'target=Default', 681 | function () { 682 | doOpen('https://www.apple.com'); 683 | }, 684 | 'openNonWhiteListed' 685 | ); 686 | createActionButton( 687 | 'target=Default (window.open)', 688 | function () { 689 | doHookOpen('https://www.apple.com'); 690 | }, 691 | 'openNonWhiteListedHook' 692 | ); 693 | createActionButton( 694 | 'target=_self', 695 | function () { 696 | doOpen('https://www.apple.com', '_self'); 697 | }, 698 | 'openNonWhiteListedSelf' 699 | ); 700 | createActionButton( 701 | 'target=_system', 702 | function () { 703 | doOpen('https://www.apple.com', '_system'); 704 | }, 705 | 'openNonWhiteListedSystem' 706 | ); 707 | createActionButton( 708 | 'target=_blank', 709 | function () { 710 | doOpen('https://www.apple.com', '_blank'); 711 | }, 712 | 'openNonWhiteListedBlank' 713 | ); 714 | createActionButton( 715 | 'target=Random', 716 | function () { 717 | doOpen('https://www.apple.com', 'random_string'); 718 | }, 719 | 'openNonWhiteListedRandom' 720 | ); 721 | createActionButton( 722 | '* target=Random, no location bar', 723 | function () { 724 | doOpen('https://www.apple.com', 'random_string', 'location=no'); 725 | }, 726 | 'openNonWhiteListedRandomNoLocation' 727 | ); 728 | 729 | // Page with redirect 730 | createActionButton( 731 | 'http://google.co.uk', 732 | function () { 733 | doOpen('https://google.co.uk', 'random_string', '', 1); 734 | }, 735 | 'openRedirect301' 736 | ); 737 | createActionButton( 738 | 'http://goo.gl/pUFqg', 739 | function () { 740 | doOpen('https://goo.gl/pUFqg', 'random_string', '', 2); 741 | }, 742 | 'openRedirect302' 743 | ); 744 | 745 | // PDF URL 746 | createActionButton( 747 | 'Remote URL', 748 | function () { 749 | doOpen('https://www.stluciadance.com/prospectus_file/sample.pdf'); 750 | }, 751 | 'openPDF' 752 | ); 753 | createActionButton( 754 | 'Local URL', 755 | function () { 756 | doOpen(localpdf, '_blank'); 757 | }, 758 | 'openPDFBlank' 759 | ); 760 | 761 | // Invalid URL 762 | createActionButton( 763 | 'Invalid Scheme', 764 | function () { 765 | doOpen('x-ttp://www.invalid.com/', '_blank'); 766 | }, 767 | 'openInvalidScheme' 768 | ); 769 | createActionButton( 770 | 'Invalid Host', 771 | function () { 772 | doOpen('https://www.inv;alid.com/', '_blank'); 773 | }, 774 | 'openInvalidHost' 775 | ); 776 | createActionButton( 777 | 'Missing Local File', 778 | function () { 779 | doOpen('nonexistent.html', '_blank'); 780 | }, 781 | 'openInvalidMissing' 782 | ); 783 | 784 | // CSS / JS injection 785 | createActionButton( 786 | 'Original Document', 787 | function () { 788 | doOpen(injecthtml, '_blank'); 789 | }, 790 | 'openOriginalDocument' 791 | ); 792 | createActionButton( 793 | 'CSS File Injection', 794 | function () { 795 | openWithStyle(injecthtml, injectcss); 796 | }, 797 | 'openCSSInjection' 798 | ); 799 | createActionButton( 800 | 'CSS File Injection (callback)', 801 | function () { 802 | openWithStyle(injecthtml, injectcss, true); 803 | }, 804 | 'openCSSInjectionCallback' 805 | ); 806 | createActionButton( 807 | 'CSS Literal Injection', 808 | function () { 809 | openWithStyle(injecthtml); 810 | }, 811 | 'openCSSLiteralInjection' 812 | ); 813 | createActionButton( 814 | 'CSS Literal Injection (callback)', 815 | function () { 816 | openWithStyle(injecthtml, null, true); 817 | }, 818 | 'openCSSLiteralInjectionCallback' 819 | ); 820 | createActionButton( 821 | 'Script File Injection', 822 | function () { 823 | openWithScript(injecthtml, injectjs); 824 | }, 825 | 'openScriptInjection' 826 | ); 827 | createActionButton( 828 | 'Script File Injection (callback)', 829 | function () { 830 | openWithScript(injecthtml, injectjs, true); 831 | }, 832 | 'openScriptInjectionCallback' 833 | ); 834 | createActionButton( 835 | 'Script Literal Injection', 836 | function () { 837 | openWithScript(injecthtml); 838 | }, 839 | 'openScriptLiteralInjection' 840 | ); 841 | createActionButton( 842 | 'Script Literal Injection (callback)', 843 | function () { 844 | openWithScript(injecthtml, null, true); 845 | }, 846 | 'openScriptLiteralInjectionCallback' 847 | ); 848 | 849 | // Open hidden 850 | createActionButton( 851 | 'Create Hidden', 852 | function () { 853 | openHidden('https://www.google.co.uk', true); 854 | }, 855 | 'openHidden' 856 | ); 857 | createActionButton( 858 | 'Show Hidden', 859 | function () { 860 | showHidden(); 861 | }, 862 | 'showHidden' 863 | ); 864 | createActionButton( 865 | 'Close Hidden', 866 | function () { 867 | closeHidden(); 868 | }, 869 | 'closeHidden' 870 | ); 871 | createActionButton( 872 | 'google.co.uk Not Hidden', 873 | function () { 874 | openHidden('https://www.google.co.uk', false); 875 | }, 876 | 'openHiddenShow' 877 | ); 878 | createActionButton( 879 | 'google.co.uk shown for 2 seconds than hidden', 880 | function () { 881 | const iab = doOpen('https://www.google.co.uk/', 'random_sting'); 882 | setTimeout(function () { 883 | iab.hide(); 884 | }, 2000); 885 | }, 886 | 'openVisibleAndHide' 887 | ); 888 | 889 | // Clearing cache 890 | createActionButton( 891 | 'Clear Browser Cache', 892 | function () { 893 | doOpen('https://www.google.co.uk', '_blank', 'clearcache=yes'); 894 | }, 895 | 'openClearCache' 896 | ); 897 | createActionButton( 898 | 'Clear Session Cache', 899 | function () { 900 | doOpen('https://www.google.co.uk', '_blank', 'clearsessioncache=yes'); 901 | }, 902 | 'openClearSessionCache' 903 | ); 904 | 905 | // Video tag 906 | createActionButton( 907 | 'Remote Video', 908 | function () { 909 | doOpen(videohtml, '_blank'); 910 | }, 911 | 'openRemoteVideo' 912 | ); 913 | createActionButton( 914 | 'Remote Need User No Video', 915 | function () { 916 | doOpen(videohtml, '_blank', 'mediaPlaybackRequiresUserAction=no'); 917 | }, 918 | 'openRemoteNeedUserNoVideo' 919 | ); 920 | createActionButton( 921 | 'Remote Need User Yes Video', 922 | function () { 923 | doOpen(videohtml, '_blank', 'mediaPlaybackRequiresUserAction=yes'); 924 | }, 925 | 'openRemoteNeedUserYesVideo' 926 | ); 927 | 928 | // Local With Anchor Tag 929 | createActionButton( 930 | 'Anchor1', 931 | function () { 932 | doOpen(localhtml + '#bogusanchor', '_blank'); 933 | }, 934 | 'openAnchor1' 935 | ); 936 | createActionButton( 937 | 'Anchor2', 938 | function () { 939 | doOpen(localhtml + '#anchor2', '_blank'); 940 | }, 941 | 'openAnchor2' 942 | ); 943 | 944 | // Hardwareback 945 | createActionButton( 946 | 'no hardwareback (defaults to yes)', 947 | function () { 948 | doOpen('https://cordova.apache.org', '_blank'); 949 | }, 950 | 'openHardwareBackDefault' 951 | ); 952 | createActionButton( 953 | 'hardwareback=yes', 954 | function () { 955 | doOpen('https://cordova.apache.org', '_blank', 'hardwareback=yes'); 956 | }, 957 | 'openHardwareBackYes' 958 | ); 959 | createActionButton( 960 | 'hardwareback=no', 961 | function () { 962 | doOpen('https://cordova.apache.org', '_blank', 'hardwareback=no'); 963 | }, 964 | 'openHardwareBackNo' 965 | ); 966 | createActionButton( 967 | 'no hardwareback -> hardwareback=no -> no hardwareback', 968 | function () { 969 | const ref = cordova.InAppBrowser.open('https://google.com', '_blank', 'location=yes' + (platformOpts ? ',' + platformOpts : '')); 970 | ref.addEventListener('loadstop', function () { 971 | ref.close(); 972 | }); 973 | ref.addEventListener('exit', function () { 974 | const ref2 = cordova.InAppBrowser.open( 975 | 'https://google.com', 976 | '_blank', 977 | 'location=yes,hardwareback=no' + (platformOpts ? ',' + platformOpts : '') 978 | ); 979 | ref2.addEventListener('loadstop', function () { 980 | ref2.close(); 981 | }); 982 | ref2.addEventListener('exit', function () { 983 | cordova.InAppBrowser.open('https://google.com', '_blank', 'location=yes' + (platformOpts ? ',' + platformOpts : '')); 984 | }); 985 | }); 986 | }, 987 | 'openHardwareBackDefaultAfterNo' 988 | ); 989 | }; 990 | -------------------------------------------------------------------------------- /types/index.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for Apache Cordova InAppBrowser plugin 2 | // Project: https://github.com/apache/cordova-plugin-inappbrowser 3 | // Definitions by: Microsoft Open Technologies Inc 4 | // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped 5 | // 6 | // Copyright (c) Microsoft Open Technologies Inc 7 | // Licensed under the MIT license. 8 | // TypeScript Version: 2.3 9 | type channel = "loadstart" | "loadstop" | "loaderror" | "exit" | "message" | "customscheme"; 10 | 11 | /** 12 | * The object returned from a call to cordova.InAppBrowser.open. 13 | * NOTE: The InAppBrowser window behaves like a standard web browser, and can't access Cordova APIs. 14 | */ 15 | interface InAppBrowser { 16 | 17 | /** 18 | * Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser. 19 | * @param url The URL to load. 20 | * @param target The target in which to load the URL, an optional parameter that defaults to _self. 21 | * @param options Options for the InAppBrowser. Optional, defaulting to: location=yes. 22 | * The options string must not contain any blank space, and each feature's 23 | * name/value pairs must be separated by a comma. Feature names are case insensitive. 24 | */ 25 | open(url: string, target?: string, options?: string): InAppBrowser; 26 | 27 | onloadstart(type: Event): void; 28 | onloadstop(type: InAppBrowserEvent): void; 29 | onloaderror(type: InAppBrowserEvent): void; 30 | onexit(type: InAppBrowserEvent): void; 31 | // addEventListener overloads 32 | /** 33 | * Adds a listener for an event from the InAppBrowser. 34 | * @param type loadstart: event fires when the InAppBrowser starts to load a URL. 35 | * loadstop: event fires when the InAppBrowser finishes loading a URL. 36 | * loaderror: event fires when the InAppBrowser encounters an error when loading a URL. 37 | * exit: event fires when the InAppBrowser window is closed. 38 | * @param callback the function that executes when the event fires. The function is 39 | * passed an InAppBrowserEvent object as a parameter. 40 | */ 41 | addEventListener(type: channel, callback: InAppBrowserEventListenerOrEventListenerObject): void; 42 | /** 43 | * Adds a listener for an event from the InAppBrowser. 44 | * @param type any custom event that might occur. 45 | * @param callback the function that executes when the event fires. The function is 46 | * passed an InAppBrowserEvent object as a parameter. 47 | */ 48 | addEventListener(type: string, callback: InAppBrowserEventListenerOrEventListenerObject): void; 49 | // removeEventListener overloads 50 | /** 51 | * Removes a listener for an event from the InAppBrowser. 52 | * @param type The event to stop listening for. 53 | * loadstart: event fires when the InAppBrowser starts to load a URL. 54 | * loadstop: event fires when the InAppBrowser finishes loading a URL. 55 | * loaderror: event fires when the InAppBrowser encounters an error when loading a URL. 56 | * exit: event fires when the InAppBrowser window is closed. 57 | * @param callback the function that executes when the event fires. The function is 58 | * passed an InAppBrowserEvent object as a parameter. 59 | */ 60 | removeEventListener(type: channel, callback: InAppBrowserEventListenerOrEventListenerObject): void; 61 | /** Closes the InAppBrowser window. */ 62 | close(): void; 63 | /** Hides the InAppBrowser window. Calling this has no effect if the InAppBrowser was already hidden. */ 64 | hide(): void; 65 | /** 66 | * Displays an InAppBrowser window that was opened hidden. Calling this has no effect 67 | * if the InAppBrowser was already visible. 68 | */ 69 | show(): void; 70 | /** 71 | * Injects JavaScript code into the InAppBrowser window. 72 | * @param script Details of the script to run, specifying either a file or code key. 73 | * @param callback The function that executes after the JavaScript code is injected. 74 | * If the injected script is of type code, the callback executes with 75 | * a single parameter, which is the return value of the script, wrapped in an Array. 76 | * For multi-line scripts, this is the return value of the last statement, 77 | * or the last expression evaluated. 78 | */ 79 | executeScript(script: { code: string } | { file: string }, callback: (result: any) => void): void; 80 | /** 81 | * Injects CSS into the InAppBrowser window. 82 | * @param css Details of the script to run, specifying either a file or code key. 83 | * @param callback The function that executes after the CSS is injected. 84 | */ 85 | insertCSS(css: { code: string } | { file: string }, callback: () => void): void; 86 | } 87 | 88 | type InAppBrowserEventListenerOrEventListenerObject = InAppBrowserEventListener | InAppBrowserEventListenerObject; 89 | 90 | type InAppBrowserEventListener = (evt: InAppBrowserEvent) => void; 91 | 92 | interface InAppBrowserEventListenerObject { 93 | handleEvent(evt: InAppBrowserEvent): void; 94 | } 95 | 96 | interface InAppBrowserEvent extends Event { 97 | /** the eventname, either loadstart, loadstop, loaderror, or exit. */ 98 | type: string; 99 | /** the URL that was loaded. */ 100 | url: string; 101 | /** the error code, only in the case of loaderror. */ 102 | code: number; 103 | /** the error message, only in the case of loaderror. */ 104 | message: string; 105 | } 106 | 107 | interface Cordova { 108 | InAppBrowser: InAppBrowser; 109 | } 110 | -------------------------------------------------------------------------------- /www/inappbrowser.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * 20 | */ 21 | 22 | (function () { 23 | const exec = require('cordova/exec'); 24 | const channel = require('cordova/channel'); 25 | const modulemapper = require('cordova/modulemapper'); 26 | const urlutil = require('cordova/urlutil'); 27 | 28 | function InAppBrowser () { 29 | this.channels = { 30 | beforeload: channel.create('beforeload'), 31 | loadstart: channel.create('loadstart'), 32 | loadstop: channel.create('loadstop'), 33 | loaderror: channel.create('loaderror'), 34 | exit: channel.create('exit'), 35 | customscheme: channel.create('customscheme'), 36 | message: channel.create('message'), 37 | download: channel.create('download'), 38 | hidecompletion: channel.create('hidecompletion') 39 | }; 40 | } 41 | 42 | InAppBrowser.prototype = { 43 | _eventHandler: function (event) { 44 | if (event && event.type in this.channels) { 45 | if (event.type === 'beforeload') { 46 | this.channels[event.type].fire(event, this._loadAfterBeforeload); 47 | } else { 48 | this.channels[event.type].fire(event); 49 | } 50 | } 51 | }, 52 | _loadAfterBeforeload: function (strUrl) { 53 | strUrl = urlutil.makeAbsolute(strUrl); 54 | exec(null, null, 'InAppBrowser', 'loadAfterBeforeload', [strUrl]); 55 | }, 56 | close: function (eventname) { 57 | exec(null, null, 'InAppBrowser', 'close', []); 58 | }, 59 | show: function (eventname) { 60 | exec(null, null, 'InAppBrowser', 'show', []); 61 | }, 62 | hide: function (eventname) { 63 | exec(null, null, 'InAppBrowser', 'hide', []); 64 | }, 65 | addEventListener: function (eventname, f) { 66 | if (eventname in this.channels) { 67 | this.channels[eventname].subscribe(f); 68 | } 69 | }, 70 | removeEventListener: function (eventname, f) { 71 | if (eventname in this.channels) { 72 | this.channels[eventname].unsubscribe(f); 73 | } 74 | }, 75 | 76 | executeScript: function (injectDetails, cb) { 77 | if (injectDetails.code) { 78 | exec(cb, null, 'InAppBrowser', 'injectScriptCode', [injectDetails.code, !!cb]); 79 | } else if (injectDetails.file) { 80 | exec(cb, null, 'InAppBrowser', 'injectScriptFile', [injectDetails.file, !!cb]); 81 | } else { 82 | throw new Error('executeScript requires exactly one of code or file to be specified'); 83 | } 84 | }, 85 | 86 | insertCSS: function (injectDetails, cb) { 87 | if (injectDetails.code) { 88 | exec(cb, null, 'InAppBrowser', 'injectStyleCode', [injectDetails.code, !!cb]); 89 | } else if (injectDetails.file) { 90 | exec(cb, null, 'InAppBrowser', 'injectStyleFile', [injectDetails.file, !!cb]); 91 | } else { 92 | throw new Error('insertCSS requires exactly one of code or file to be specified'); 93 | } 94 | }, 95 | 96 | addDownloadListener: function (success, error) { 97 | exec(success, error, 'InAppBrowser', 'downloadListener'); 98 | } 99 | }; 100 | 101 | module.exports = function (strUrl, strWindowName, strWindowFeatures, preloadCode, callbacks) { 102 | // Don't catch calls that write to existing frames (e.g. named iframes). 103 | if (window.frames && window.frames[strWindowName]) { 104 | const origOpenFunc = modulemapper.getOriginalSymbol(window, 'open'); 105 | return origOpenFunc.apply(window, arguments); 106 | } 107 | 108 | strUrl = urlutil.makeAbsolute(strUrl); 109 | const iab = new InAppBrowser(); 110 | 111 | callbacks = callbacks || {}; 112 | for (const callbackName in callbacks) { 113 | iab.addEventListener(callbackName, callbacks[callbackName]); 114 | } 115 | 116 | const cb = function (eventname) { 117 | iab._eventHandler(eventname); 118 | }; 119 | 120 | strWindowFeatures = strWindowFeatures || ''; 121 | 122 | exec(cb, cb, 'InAppBrowser', 'open', [strUrl, strWindowName, strWindowFeatures, preloadCode]); 123 | return iab; 124 | }; 125 | })(); 126 | --------------------------------------------------------------------------------