├── .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
├── .ratignore
├── CONTRIBUTING.md
├── LICENSE
├── NOTICE
├── README.md
├── RELEASENOTES.md
├── package-lock.json
├── package.json
├── plugin.xml
├── src
├── android
│ └── NetworkManager.java
├── browser
│ └── network.js
├── ios
│ ├── CDVConnection.h
│ ├── CDVConnection.m
│ ├── CDVReachability.h
│ └── CDVReachability.m
└── windows
│ └── NetworkInfoProxy.js
├── tests
├── package.json
├── plugin.xml
└── tests.js
├── types
└── index.d.ts
└── www
├── Connection.js
└── network.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 Network Information 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 |
20 | extends: '@cordova/eslint-config/browser'
21 |
22 | overrides:
23 | - files: [tests/**/*.js]
24 | extends: '@cordova/eslint-config/node-tests'
25 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text eol=lf
--------------------------------------------------------------------------------
/.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 | * Slack Community Chat: https://cordova.slack.com (you can sign-up at http://slack.cordova.io/)
17 | * StackOverflow: https://stackoverflow.com/questions/tagged/cordova using the tag `cordova`
18 |
19 | ---
20 |
21 | If you are using a tool that uses Cordova internally, like e.g. Ionic, check their support channels:
22 |
23 | * **Ionic Framework**
24 | * [Ionic Community Forum](https://forum.ionicframework.com/)
25 | * [Ionic Worldwide Slack](https://ionicworldwide.herokuapp.com/)
26 | * **PhoneGap**
27 | * [PhoneGap Developer Community](https://forums.adobe.com/community/phonegap)
28 |
--------------------------------------------------------------------------------
/.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 |
27 | pull_request:
28 | paths-ignore:
29 | - '**.md'
30 | - 'LICENSE'
31 | - '.eslint*'
32 |
33 | jobs:
34 | test:
35 | name: Android ${{ matrix.versions.android }} Test
36 | runs-on: ubuntu-latest
37 | continue-on-error: true
38 |
39 | # hoist configurations to top that are expected to be updated
40 | env:
41 | # Storing a copy of the repo
42 | repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
43 |
44 | node-version: 20
45 |
46 | # These are the default Java configurations used by most tests.
47 | # To customize these options, add "java-distro" or "java-version" to the strategy matrix with its overriding value.
48 | default_java-distro: temurin
49 | default_java-version: 17
50 |
51 | # These are the default Android System Image configurations used by most tests.
52 | # To customize these options, add "system-image-arch" or "system-image-target" to the strategy matrix with its overriding value.
53 | default_system-image-arch: x86_64
54 | default_system-image-target: google_apis # Most system images have a google_api option. Set this as default.
55 |
56 | # configurations for each testing strategy (test matrix)
57 | strategy:
58 | matrix:
59 | versions:
60 | - android: 7
61 | android-api: 24
62 |
63 | - android: 7.1
64 | android-api: 25
65 |
66 | - android: 8
67 | android-api: 26
68 |
69 | - android: 8.1
70 | android-api: 27
71 | system-image-arch: x86
72 |
73 | - android: 9
74 | android-api: 28
75 |
76 | - android: 10
77 | android-api: 29
78 |
79 | - android: 11
80 | android-api: 30
81 |
82 | - android: 12
83 | android-api: 31
84 |
85 | - android: 12L
86 | android-api: 32
87 |
88 | - android: 13
89 | android-api: 33
90 |
91 | - android: 14
92 | android-api: 34
93 |
94 | timeout-minutes: 60
95 |
96 | steps:
97 | - uses: actions/checkout@v4
98 | - uses: actions/setup-node@v4
99 | with:
100 | node-version: ${{ env.node-version }}
101 | - uses: actions/setup-java@v4
102 | env:
103 | java-version: ${{ matrix.versions.java-version == '' && env.default_java-version || matrix.versions.java-version }}
104 | java-distro: ${{ matrix.versions.java-distro == '' && env.default_java-distro || matrix.versions.java-distro }}
105 | with:
106 | distribution: ${{ env.java-distro }}
107 | java-version: ${{ env.java-version }}
108 |
109 | - name: Enable KVM group perms
110 | run: |
111 | echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
112 | sudo udevadm control --reload-rules
113 | sudo udevadm trigger --name-match=kvm
114 |
115 | - name: Run Environment Information
116 | run: |
117 | node --version
118 | npm --version
119 | java -version
120 |
121 | - name: Run npm install
122 | run: |
123 | export PATH="/usr/local/lib/android/sdk/platform-tools":$PATH
124 | export JAVA_HOME=$JAVA_HOME_11_X64
125 | npm i -g cordova@latest
126 | npm ci
127 |
128 | - name: Run paramedic install
129 | if: ${{ endswith(env.repo, '/cordova-paramedic') != true }}
130 | run: npm i -g github:apache/cordova-paramedic
131 |
132 | - uses: reactivecircus/android-emulator-runner@v2
133 | env:
134 | system-image-arch: ${{ matrix.versions.system-image-arch == '' && env.default_system-image-arch || matrix.versions.system-image-arch }}
135 | system-image-target: ${{ matrix.versions.system-image-target == '' && env.default_system-image-target || matrix.versions.system-image-target }}
136 | with:
137 | api-level: ${{ matrix.versions.android-api }}
138 | target: ${{ env.system-image-target }}
139 | arch: ${{ env.system-image-arch }}
140 | force-avd-creation: false
141 | disable-animations: false
142 | emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim
143 | script: echo "Pregenerate the AVD before running Paramedic"
144 |
145 | - name: Run paramedic tests
146 | uses: reactivecircus/android-emulator-runner@v2
147 | env:
148 | system-image-arch: ${{ matrix.versions.system-image-arch == '' && env.default_system-image-arch || matrix.versions.system-image-arch }}
149 | system-image-target: ${{ matrix.versions.system-image-target == '' && env.default_system-image-target || matrix.versions.system-image-target }}
150 | test_config: 'android-${{ matrix.versions.android }}.config.json'
151 | # Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed.
152 | test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }}
153 | paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }}
154 | with:
155 | api-level: ${{ matrix.versions.android-api }}
156 | target: ${{ env.system-image-target }}
157 | arch: ${{ env.system-image-arch }}
158 | force-avd-creation: false
159 | disable-animations: false
160 | emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim
161 | script: ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }}
162 |
--------------------------------------------------------------------------------
/.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: 20
43 |
44 | steps:
45 | - uses: actions/checkout@v4
46 | - uses: actions/setup-node@v4
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: 20
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-12
54 | ios-version: 15.x
55 | xcode-version: 13.x
56 |
57 | - os-version: macos-14
58 | ios-version: 16.x
59 | xcode-version: 14.x
60 |
61 | - os-version: macos-14
62 | ios-version: 17.x
63 | xcode-version: 15.x
64 |
65 | steps:
66 | - uses: actions/checkout@v4
67 | - uses: actions/setup-node@v4
68 | with:
69 | node-version: ${{ env.node-version }}
70 | - uses: maxim-lobanov/setup-xcode@60606e260d2fc5762a71e64e74b2174e8ea3c8bd
71 | env:
72 | xcode-version: ${{ matrix.versions.xcode-version == '' && env.default_xcode-version || matrix.versions.xcode-version }}
73 | with:
74 | xcode-version: ${{ env.xcode-version }}
75 |
76 | - name: Run Environment Information
77 | run: |
78 | node --version
79 | npm --version
80 | xcodebuild -version
81 |
82 | - name: Run npm install
83 | run: |
84 | npm i -g cordova@latest ios-deploy@latest
85 | npm ci
86 |
87 | - name: Run paramedic install
88 | if: ${{ endswith(env.repo, '/cordova-paramedic') != true }}
89 | run: npm i -g github:apache/cordova-paramedic
90 |
91 | - name: Run paramedic tests
92 | env:
93 | test_config: 'ios-${{ matrix.versions.ios-version }}.config.json'
94 | # Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed.
95 | test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }}
96 | paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }}
97 | run: ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }}
98 |
--------------------------------------------------------------------------------
/.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: 20
38 |
39 | steps:
40 | - uses: actions/checkout@v4
41 | - uses: actions/setup-node@v4
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 |
15 | node_modules
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | .*
2 | tests
3 |
--------------------------------------------------------------------------------
/.ratignore:
--------------------------------------------------------------------------------
1 | CDVReachability.m
2 | CDVReachability.h
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 |
7 | This product includes software developed by Apple Inc. License can be found in the header of the affected files. (src/ios/CDVReachability.h, src/ios/CDVReachability.m)
8 |
9 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Network Information
3 | description: Get information about wireless connectivity.
4 | ---
5 |
23 |
24 | # cordova-plugin-network-information
25 |
26 | [](https://github.com/apache/cordova-plugin-network-information/actions/workflows/android.yml) [](https://github.com/apache/cordova-plugin-network-information/actions/workflows/chrome.yml) [](https://github.com/apache/cordova-plugin-network-information/actions/workflows/ios.yml) [](https://github.com/apache/cordova-plugin-network-information/actions/workflows/lint.yml)
27 |
28 |
29 | This plugin provides an implementation of an old version of the
30 | [Network Information API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/).
31 | It provides information about the device's cellular and
32 | wifi connection, and whether the device has an internet connection.
33 |
34 | > To get a few ideas how to use the plugin, check out the [sample](#sample) at the bottom of this page or go straight to the [reference](#reference) content.
35 |
36 | ## Installation
37 |
38 | cordova plugin add cordova-plugin-network-information
39 |
40 | ## Supported Platforms
41 |
42 | - Android
43 | - Browser
44 | - iOS
45 | - Windows
46 |
47 | # Connection
48 |
49 | > The `connection` object, exposed via `navigator.connection`, provides information about the device's cellular and wifi connection.
50 |
51 | ## Properties
52 |
53 | - connection.type
54 |
55 | ## Constants
56 |
57 | - Connection.UNKNOWN
58 | - Connection.ETHERNET
59 | - Connection.WIFI
60 | - Connection.CELL_2G
61 | - Connection.CELL_3G
62 | - Connection.CELL_4G
63 | - Connection.CELL
64 | - Connection.NONE
65 |
66 | ## connection.type
67 |
68 | This property offers a fast way to determine the device's network
69 | connection state, and type of connection.
70 |
71 | ### Quick Example
72 |
73 | ```js
74 | function checkConnection() {
75 | var networkState = navigator.connection.type;
76 |
77 | var states = {};
78 | states[Connection.UNKNOWN] = 'Unknown connection';
79 | states[Connection.ETHERNET] = 'Ethernet connection';
80 | states[Connection.WIFI] = 'WiFi connection';
81 | states[Connection.CELL_2G] = 'Cell 2G connection';
82 | states[Connection.CELL_3G] = 'Cell 3G connection';
83 | states[Connection.CELL_4G] = 'Cell 4G connection';
84 | states[Connection.CELL] = 'Cell generic connection';
85 | states[Connection.NONE] = 'No network connection';
86 |
87 | alert('Connection type: ' + states[networkState]);
88 | }
89 |
90 | checkConnection();
91 | ```
92 |
93 | ### iOS Quirks
94 |
95 | -
183 |
184 | The code examples in this section show examples of changing app behavior using the online and offline events and your network connection status.
185 |
186 | To start with, create a new FileEntry object (data.txt) to use for sample data. Call this function from the `deviceready` handler.
187 |
188 | >*Note* This code example requires the File plugin.
189 |
190 | ```js
191 | var dataFileEntry;
192 |
193 | function createSomeData() {
194 |
195 | window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
196 |
197 | console.log('file system open: ' + fs.name);
198 | // Creates a new file or returns an existing file.
199 | fs.root.getFile("data.txt", { create: true, exclusive: false }, function (fileEntry) {
200 |
201 | dataFileEntry = fileEntry;
202 |
203 | }, onErrorCreateFile);
204 |
205 | }, onErrorLoadFs);
206 | }
207 | ```
208 |
209 | Next, add listeners for the online and offline events in the `deviceready` handler.
210 |
211 | ```js
212 | document.addEventListener("offline", onOffline, false);
213 | document.addEventListener("online", onOnline, false);
214 | ```
215 |
216 | The app's `onOnline` function handles the online event. In the event handler, check the current network state. In this app, treat any connection type as good except Connection.NONE. If you have a connection, you try to upload a file.
217 |
218 | ```js
219 | function onOnline() {
220 | // Handle the online event
221 | var networkState = navigator.connection.type;
222 |
223 | if (networkState !== Connection.NONE) {
224 | if (dataFileEntry) {
225 | tryToUploadFile();
226 | }
227 | }
228 | display('Connection type: ' + networkState);
229 | }
230 | ```
231 |
232 | When the online event fires in the preceding code, call the app's `tryToUploadFile` function.
233 |
234 | If the upload fails, then call the app's `offlineWrite` function to save the current data somewhere.
235 |
236 | >*Note* For simplicity, file reading & writing was omitted. Refer to the [cordova-plugin-file](https://github.com/apache/cordova-plugin-file#cordova-plugin-file) documentation for more information on file handling.
237 |
238 | ```js
239 | function tryToUploadFile() {
240 | // !! Assumes variable fileURL contains a valid URL to a text file on the device,
241 | var fileURL = getDataFileEntry().toURL();
242 |
243 | getFileBlobSomehow(fileURL, function(fileBlob) {
244 | var success = function (r) {
245 | console.log("Response = " + r.response);
246 | display("Uploaded. Response: " + r.response);
247 | };
248 |
249 | var fail = function (error) {
250 | console.log("An error has occurred: Code = " + error.code || error.status);
251 | offlineWrite("Failed to upload: some offline data");
252 | }
253 |
254 | var xhr = new XMLHttpRequest();
255 |
256 | xhr.onerror = fail;
257 | xhr.ontimeout = fail;
258 | xhr.onload = function() {
259 | // If the response code was successful...
260 | if (xhr.status >= 200 && xhr.status < 400) {
261 | success(xhr);
262 | }
263 | else {
264 | fail(xhr)
265 | }
266 | }
267 |
268 | // Make sure you add the domain of your server URL to the
269 | // Content-Security-Policy element in index.html.
270 | xhr.open("POST", encodeURI(SERVER));
271 |
272 | xhr.setRequestHeader("Content-Type", "text/plain");
273 |
274 | // The server request handler could read this header to
275 | // set the filename.
276 | xhr.setRequestHeader("X-Filename", fileURL.substr(fileURL.lastIndexOf("/") + 1));
277 |
278 | xhr.send(fileBlob);
279 | });
280 | };
281 | ```
282 |
283 | Here is the code for the `offlineWrite` function.
284 |
285 | >*Note* This code examples requires the File plugin.
286 |
287 | ```js
288 | function offlineWrite(offlineData) {
289 | // Create a FileWriter object for our FileEntry.
290 | dataFileEntry.createWriter(function (fileWriter) {
291 |
292 | fileWriter.onwriteend = function () {
293 | console.log("Successful file write...");
294 | display(offlineData);
295 | };
296 |
297 | fileWriter.onerror = function (e) {
298 | console.log("Failed file write: " + e.toString());
299 | };
300 |
301 | fileWriter.write(offlineData);
302 | });
303 | }
304 | ```
305 |
306 | If the offline event occurs, just do something like notify the user (for this example, just log it).
307 |
308 | ```js
309 | function onOffline() {
310 | // Handle the offline event
311 | console.log("lost connection");
312 | }
313 | ```
314 |
--------------------------------------------------------------------------------
/RELEASENOTES.md:
--------------------------------------------------------------------------------
1 |
21 | # Release Notes
22 |
23 | ### 3.0.0 (Jun 03, 2021)
24 | - release 3.0.0 audit fix
25 | - ci: add node-14.x to workflow
26 | - ci(travis): update osx xcode image
27 | - ci(travis): updates **Android** API level
28 | - **Android** - Fixes bug onConnect does not work as expected [#110](https://github.com/apache/cordova-plugin-network-information/issues/110)
29 | - chore(npm): use short notation in `package.json`
30 | - chore: adds package-lock file
31 | - chore: bumps version to 3.0.0-dev in test files
32 | - refactor: Removed all references of deprecated navigator.network
33 | - docs: Replaced FileTransfer example with a XHR example
34 | - docs: Note on background usage
35 | - docs: Removed apache issue tracker link
36 | - docs: Removed **iOS** 7 quirk
37 | - refactor(eslint): use cordova-eslint
38 | - chore(asf): update git notification settings
39 | - Update CONTRIBUTING.md
40 | - chore(npm): improve ignore list
41 | - ci: updates Node.js versions
42 | - ci(appveyor): remove node 6, add node 12
43 | - ci(travis): upgrade to node 8
44 |
45 | ### 2.0.2 (Jun 19, 2019)
46 |
47 | - fix(android): Fix bug [cordova-plugin-network-information] connection info is not reliable on Android 6 ([#74](https://github.com/apache/cordova-plugin-network-information/issues/74)) ([`db0d4b5`](https://github.com/apache/cordova-plugin-network-information/commit/db0d4b5), [`9a45d63`](https://github.com/apache/cordova-plugin-network-information/commit/9a45d63), [`60ab69f`](https://github.com/apache/cordova-plugin-network-information/commit/60ab69f), [`acc02f2`](https://github.com/apache/cordova-plugin-network-information/commit/acc02f2), [`0869800`](https://github.com/apache/cordova-plugin-network-information/commit/0869800), [`394452a`](https://github.com/apache/cordova-plugin-network-information/commit/394452a), [`cafdd67`](https://github.com/apache/cordova-plugin-network-information/commit/cafdd67))
48 | - chore(release): fix repo and issue link ([`9ec1e21`](https://github.com/apache/cordova-plugin-network-information/commit/9ec1e21))
49 | - docs: remove outdated translations ([`24e50f8`](https://github.com/apache/cordova-plugin-network-information/commit/24e50f8))
50 | - build: add .npmignore to remove unneeded files from npm package ([`d31e135`](https://github.com/apache/cordova-plugin-network-information/commit/d31e135))
51 | - build: add .gitattributes to force LF (instead of possible CRLF on Windows) ([`f35341e`](https://github.com/apache/cordova-plugin-network-information/commit/f35341e))
52 | - ci(travis): Update Travis CI configuration for new paramedic ([#89](https://github.com/apache/cordova-plugin-network-information/issues/89)) ([`102f757`](https://github.com/apache/cordova-plugin-network-information/commit/102f757))
53 | - ci(travis): add android-28 ([`27b0e39`](https://github.com/apache/cordova-plugin-network-information/commit/27b0e39))
54 | - ci: drop Node.js v4 support ([#87](https://github.com/apache/cordova-plugin-network-information/issues/87)) ([`5158556`](https://github.com/apache/cordova-plugin-network-information/commit/5158556))
55 | - chore(github): Add or update GitHub pull request and issue template ([`0cd2771`](https://github.com/apache/cordova-plugin-network-information/commit/0cd2771))
56 | - docs: remove JIRA link ([`0796cf9`](https://github.com/apache/cordova-plugin-network-information/commit/0796cf9))
57 | - ci: also accept terms for android sdk `android-27` ([`2cde33a`](https://github.com/apache/cordova-plugin-network-information/commit/2cde33a))
58 | - ci(travis): [CB-13757](https://issues.apache.org/jira/browse/CB-13757) Add build-tools-26.0.2 to travis ([`5b0933d`](https://github.com/apache/cordova-plugin-network-information/commit/5b0933d), [`e816db4`](https://github.com/apache/cordova-plugin-network-information/commit/e816db4))
59 | - chore: Fix release notes ([#61](https://github.com/apache/cordova-plugin-network-information/issues/61)) ([`629a6ab`](https://github.com/apache/cordova-plugin-network-information/commit/629a6ab))
60 |
61 | ### 2.0.1 (Dec 27, 2017)
62 | * [CB-13708](https://issues.apache.org/jira/browse/CB-13708) Fix to allow 2.0.0 version install (#60)
63 |
64 | ### 2.0.0 (Dec 15, 2017)
65 | * [CB-13663](https://issues.apache.org/jira/browse/CB-13663) : Removed deprecated platforms
66 |
67 | ### 1.3.4 (Nov 06, 2017)
68 | * [CB-12751](https://issues.apache.org/jira/browse/CB-12751) (ios) Fix connection type when airplane mode is on
69 | * [CB-13299](https://issues.apache.org/jira/browse/CB-13299) (CI) Fix **Android** builds
70 | * [CB-12895](https://issues.apache.org/jira/browse/CB-12895) added `eslint` and removed `jshint`
71 | * [CB-13028](https://issues.apache.org/jira/browse/CB-13028) (CI) **Browser** builds on Travis and AppVeyor
72 | * [CB-12847](https://issues.apache.org/jira/browse/CB-12847) added `bugs` entry to `package.json`.
73 |
74 | ### 1.3.3 (Apr 27, 2017)
75 | * [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Add **Android 6.0** build badge to `README`
76 | * [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder
77 |
78 | ### 1.3.2 (Feb 28, 2017)
79 | * [CB-12369](https://issues.apache.org/jira/browse/CB-12369) Add plugin typings from `DefinitelyTyped`
80 | * [CB-12363](https://issues.apache.org/jira/browse/CB-12363) Added build badges for **iOS 9.3** and **iOS 10.0**
81 | * [CB-11838](https://issues.apache.org/jira/browse/CB-11838) **iOS:** Unregister callback function at the right timing.
82 | * [CB-12230](https://issues.apache.org/jira/browse/CB-12230) Removed **Windows 8.1** build badges
83 |
84 | ### 1.3.1 (Dec 07, 2016)
85 | * [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 1.3.1
86 | * [CB-11230](https://issues.apache.org/jira/browse/CB-11230) [CB-11505](https://issues.apache.org/jira/browse/CB-11505) iOS: Add compatibility with IPv6
87 | * [CB-11917](https://issues.apache.org/jira/browse/CB-11917) - Remove pull request template checklist item: "iCLA has been submitted…"
88 | * [CB-11832](https://issues.apache.org/jira/browse/CB-11832) Incremented plugin version.
89 |
90 | ### 1.3.0 (Sep 08, 2016)
91 | * [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies
92 | * [CB-11734](https://issues.apache.org/jira/browse/CB-11734) Network Plugin uses `Android Log class` and not `Cordova LOG class`
93 | * [CB-11300](https://issues.apache.org/jira/browse/CB-11300) (**android**) Recognize `2G`, `3G` and `4G` network connection subtype names
94 | * Update `NetworkManager.java`
95 | * Detection of Ethernet Network Type on **Android**
96 | * fixed two potential memory leaks when doing Analyze on **iOS 9**
97 | * [CB-11384](https://issues.apache.org/jira/browse/CB-11384) **android**: Does not pass sonarqube scan
98 | * Add badges for paramedic builds on Jenkins
99 | * Add pull request template.
100 | * Readme: Add fenced code blocks with langauage hints
101 | * [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to README.md
102 |
103 | ### 1.2.1 (Apr 15, 2016)
104 | * [CB-10763](https://issues.apache.org/jira/browse/CB-10763) Remove emoji in `cordova-plugin-network-information`
105 | * [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add `JSHint` for plugins
106 |
107 | ### 1.2.0 (Jan 15, 2016)
108 | * Adding `CoreTelephony` to `plugin.xml`
109 | * Adding notification for `CT radio` information
110 | * Adding `CT radio` information
111 | * [CB-10160](https://issues.apache.org/jira/browse/CB-10160) Fixed the case mismatch issue
112 |
113 | ### 1.1.0 (Nov 18, 2015)
114 | * [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest
115 | * Fixing contribute link.
116 | * These notifications are objects so their address always evaluates to true.
117 | * Update `NetworkManager.java`
118 | * [CB-9542](https://issues.apache.org/jira/browse/CB-9542) `Browser Proxy` not defined correctly
119 | * Solved `toLowerCase` issue with `Locale.US`
120 |
121 | ### 1.0.1 (Jun 17, 2015)
122 | * Adding .ratignore file.
123 | * [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-network-information documentation translation: cordova-plugin-network-information
124 | * fix npm md issue
125 |
126 | ### 1.0.0 (Apr 15, 2015)
127 | * [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump
128 | * [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name
129 | * [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id
130 | * [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id
131 | * [CB-8185](https://issues.apache.org/jira/browse/CB-8185) Fixes typo in `cordova.platformId`
132 | * Use TRAVIS_BUILD_DIR, install paramedic by npm
133 | * [CB-8185](https://issues.apache.org/jira/browse/CB-8185) Use `navigator.onLine` as connection information source on browser platform
134 | * [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme
135 | * [CB-8659](https://issues.apache.org/jira/browse/CB-8659): ios: 4.0.x Compatibility: Remove use of initWebView method
136 | * [CB-8573](https://issues.apache.org/jira/browse/CB-8573) Integrate TravisCI
137 | * [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-network-information documentation translation: cordova-plugin-network-information
138 | * [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file
139 |
140 | ### 0.2.15 (Feb 04, 2015)
141 | * [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Network status change support on Windows
142 | * [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Fixes the way we detect online status on Windows
143 | * [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Add Windows platform quirks
144 | * [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Add Windows section to Network Information plugin
145 |
146 | ### 0.2.14 (Dec 02, 2014)
147 | * [CB-7976](https://issues.apache.org/jira/browse/CB-7976) **Android**: Use webView's context rather than Activity's context for intent receiver
148 | * [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-network-information documentation translation: cordova-plugin-network-information
149 |
150 | ### 0.2.13 (Oct 03, 2014)
151 | * [CB-7595](https://issues.apache.org/jira/browse/CB-7595): Android L changes the type from Mobile to Cellular, I'm pretty sure this isn't documented
152 |
153 | ### 0.2.12 (Sep 17, 2014)
154 | * [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-network-information documentation translation
155 | * Fix network information type exception on fxos 2
156 | * Added support for the browser
157 | * [CB-6724](https://issues.apache.org/jira/browse/CB-6724) added documentation for manual tests
158 | * remove reference to test assets, they are optional
159 | * Renamed test dir and added nested plugin.xml
160 | * [CB-6964](https://issues.apache.org/jira/browse/CB-6964) ported manual tests
161 | * Port network tests to plugin-test-framework
162 | * Fix naviagtor typo
163 |
164 | ### 0.2.11 (Aug 06, 2014)
165 | * **FFOS** update NetworkProxy.js
166 | * [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs
167 | * [CB-7019](https://issues.apache.org/jira/browse/CB-7019) Updated version and RELEASENOTES.md for release 0.2.10
168 | * Fixed docs for online/offline event being backwards
169 |
170 | ### 0.2.10 (Jun 24, 2014)
171 | * [CB-6907](https://issues.apache.org/jira/browse/CB-6907): [android] Don't crash on startup if no networks available
172 |
173 | ### 0.2.9 (Jun 05, 2014)
174 | * updated notice file to include missing license
175 | * Cached extra info to better detect changes.
176 | * [CB-6809](https://issues.apache.org/jira/browse/CB-6809) Add license to CONTRIBUTING.md
177 | * [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md
178 | * [CB-6350](https://issues.apache.org/jira/browse/CB-6350) - Fix networkStatusForFlags return value type to work with 64-bit iOS (closes #8)
179 | * Initial version of firefox os network information plugin
180 | * there was an error in the object definition
181 |
182 | ### 0.2.8 (Apr 17, 2014)
183 | * [CB-6342](https://issues.apache.org/jira/browse/CB-6342): [iOS] iOS reports a cellular connection even when in Airplane mode
184 | * [CB-6422](https://issues.apache.org/jira/browse/CB-6422): [windows8] use cordova/exec/proxy
185 | * [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers
186 | * [CB-6465](https://issues.apache.org/jira/browse/CB-6465): Add license headers to Tizen code
187 | * Add NOTICE file
188 |
189 | ### 0.2.7 (Feb 05, 2014)
190 | * Initial implementation of Tizen plugin.
191 |
192 | ### 0.2.6 (Jan 02, 2014)
193 | * [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc/index.md for netinfo plugin
194 |
195 | ### 0.2.5 (Dec 4, 2013)
196 | * [ubuntu] specify policy_group
197 | * add ubuntu platform
198 | * Added amazon-fireos platform. Change to use amazon-fireos as the platform if user agent string contains 'cordova-amazon-fireos'
199 |
200 | ### 0.2.4 (Oct 28, 2013)
201 | * [CB-5128](https://issues.apache.org/jira/browse/CB-5128): add repo + issue tag to plugin.xml for network information plugin
202 | * [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch.
203 |
204 | ### 0.2.3 (Sept 25, 2013)
205 | * [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version
206 | * [windows8] commandProxy was moved
207 | * [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.network-information to org.apache.cordova.network-information
208 | * removed duplicate comment line from plugin.xml
209 | * added Network APIs for FirefoxOS
210 | * Rename CHANGELOG.md -> RELEASENOTES.md
211 | * [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch.
212 |
213 | ### 0.2.1 (Sept 5, 2013)
214 | * [CB-4432](https://issues.apache.org/jira/browse/CB-4432) copyright notice change
215 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cordova-plugin-network-information",
3 | "version": "3.0.1-dev",
4 | "description": "Cordova Network Information Plugin",
5 | "types": "./types/index.d.ts",
6 | "cordova": {
7 | "id": "cordova-plugin-network-information",
8 | "platforms": [
9 | "android",
10 | "ios",
11 | "windows",
12 | "browser"
13 | ]
14 | },
15 | "repository": "github:apache/cordova-plugin-network-information",
16 | "bugs": "https://github.com/apache/cordova-plugin-network-information/issues",
17 | "keywords": [
18 | "cordova",
19 | "network",
20 | "information",
21 | "ecosystem:cordova",
22 | "cordova-android",
23 | "cordova-ios",
24 | "cordova-windows",
25 | "cordova-browser"
26 | ],
27 | "scripts": {
28 | "test": "npm run lint",
29 | "lint": "eslint ."
30 | },
31 | "author": "Apache Software Foundation",
32 | "license": "Apache-2.0",
33 | "engines": {
34 | "cordovaDependencies": {
35 | "3.0.0": {
36 | "cordova": ">=9"
37 | },
38 | "4.0.0": {
39 | "cordova": ">100"
40 | }
41 | }
42 | },
43 | "devDependencies": {
44 | "@cordova/eslint-config": "^3.0.0"
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/plugin.xml:
--------------------------------------------------------------------------------
1 |
2 |
20 |
21 |
25 |
26 | Network Information
27 | Cordova Network Information Plugin
28 | Apache 2.0
29 | cordova,network,information
30 | https://github.com/apache/cordova-plugin-network-information
31 | https://github.com/apache/cordova-plugin-network-information/issues
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 |
--------------------------------------------------------------------------------
/src/android/NetworkManager.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.networkinformation;
20 |
21 | import org.apache.cordova.CallbackContext;
22 | import org.apache.cordova.CordovaInterface;
23 | import org.apache.cordova.CordovaPlugin;
24 | import org.apache.cordova.LOG;
25 | import org.apache.cordova.PluginResult;
26 | import org.apache.cordova.CordovaWebView;
27 | import org.json.JSONArray;
28 | import org.json.JSONException;
29 | import org.json.JSONObject;
30 |
31 | import android.content.BroadcastReceiver;
32 | import android.content.Context;
33 | import android.content.Intent;
34 | import android.content.IntentFilter;
35 | import android.net.ConnectivityManager;
36 | import android.net.NetworkInfo;
37 | import android.os.Build;
38 |
39 | import java.util.Locale;
40 |
41 | public class NetworkManager extends CordovaPlugin {
42 |
43 | public static int NOT_REACHABLE = 0;
44 | public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1;
45 | public static int REACHABLE_VIA_WIFI_NETWORK = 2;
46 |
47 | public static final String WIFI = "wifi";
48 | public static final String WIMAX = "wimax";
49 | // mobile
50 | public static final String MOBILE = "mobile";
51 |
52 | // Android L calls this Cellular, because I have no idea!
53 | public static final String CELLULAR = "cellular";
54 | // 2G network types
55 | public static final String TWO_G = "2g";
56 | public static final String GSM = "gsm";
57 | public static final String GPRS = "gprs";
58 | public static final String EDGE = "edge";
59 | // 3G network types
60 | public static final String THREE_G = "3g";
61 | public static final String CDMA = "cdma";
62 | public static final String UMTS = "umts";
63 | public static final String HSPA = "hspa";
64 | public static final String HSUPA = "hsupa";
65 | public static final String HSDPA = "hsdpa";
66 | public static final String ONEXRTT = "1xrtt";
67 | public static final String EHRPD = "ehrpd";
68 | // 4G network types
69 | public static final String FOUR_G = "4g";
70 | public static final String LTE = "lte";
71 | public static final String UMB = "umb";
72 | public static final String HSPA_PLUS = "hspa+";
73 | // return type
74 | public static final String TYPE_UNKNOWN = "unknown";
75 | public static final String TYPE_ETHERNET = "ethernet";
76 | public static final String TYPE_ETHERNET_SHORT = "eth";
77 | public static final String TYPE_WIFI = "wifi";
78 | public static final String TYPE_2G = "2g";
79 | public static final String TYPE_3G = "3g";
80 | public static final String TYPE_4G = "4g";
81 | public static final String TYPE_NONE = "none";
82 |
83 | private static final String LOG_TAG = "NetworkManager";
84 |
85 | private CallbackContext connectionCallbackContext;
86 |
87 | ConnectivityManager sockMan;
88 | BroadcastReceiver receiver;
89 | private String lastTypeOfNetwork;
90 |
91 | /**
92 | * Sets the context of the Command. This can then be used to do things like
93 | * get file paths associated with the Activity.
94 | *
95 | * @param cordova The context of the main Activity.
96 | * @param webView The CordovaWebView Cordova is running in.
97 | */
98 | public void initialize(CordovaInterface cordova, CordovaWebView webView) {
99 | super.initialize(cordova, webView);
100 | this.sockMan = (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
101 | this.connectionCallbackContext = null;
102 |
103 | this.registerConnectivityActionReceiver();
104 | }
105 |
106 | /**
107 | * Executes the request and returns PluginResult.
108 | *
109 | * @param action The action to execute.
110 | * @param args JSONArry of arguments for the plugin.
111 | * @param callbackContext The callback id used when calling back into JavaScript.
112 | * @return True if the action was valid, false otherwise.
113 | */
114 | public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
115 | if (action.equals("getConnectionInfo")) {
116 | this.connectionCallbackContext = callbackContext;
117 | NetworkInfo info = sockMan.getActiveNetworkInfo();
118 | String connectionType = this.getTypeOfNetworkFallbackToTypeNoneIfNotConnected(info);
119 | PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType);
120 | pluginResult.setKeepCallback(true);
121 | callbackContext.sendPluginResult(pluginResult);
122 | return true;
123 | }
124 | return false;
125 | }
126 |
127 | /**
128 | * Stop network receiver.
129 | */
130 | public void onDestroy() {
131 | this.unregisterReceiver();
132 | }
133 |
134 | @Override
135 | public void onPause(boolean multitasking) {
136 | this.unregisterReceiver();
137 | }
138 |
139 | @Override
140 | public void onResume(boolean multitasking) {
141 | super.onResume(multitasking);
142 |
143 | this.unregisterReceiver();
144 | this.registerConnectivityActionReceiver();
145 | }
146 |
147 | //--------------------------------------------------------------------------
148 | // LOCAL METHODS
149 | //--------------------------------------------------------------------------
150 |
151 | private void registerConnectivityActionReceiver() {
152 | // We need to listen to connectivity events to update navigator.connection
153 | IntentFilter intentFilter = new IntentFilter();
154 | intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
155 | if (this.receiver == null) {
156 | this.receiver = new BroadcastReceiver() {
157 | @Override
158 | public void onReceive(Context context, Intent intent) {
159 | // (The null check is for the ARM Emulator, please use Intel Emulator for better results)
160 | if (NetworkManager.this.webView != null) {
161 | updateConnectionInfo(sockMan.getActiveNetworkInfo());
162 | }
163 |
164 | String connectionType;
165 | if (NetworkManager.this.lastTypeOfNetwork == null) {
166 | connectionType = TYPE_NONE;
167 | } else {
168 | connectionType = NetworkManager.this.lastTypeOfNetwork;
169 | }
170 |
171 | // Lollipop always returns false for the EXTRA_NO_CONNECTIVITY flag => fix for Android M and above.
172 | if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && TYPE_NONE.equals(connectionType)) {
173 | boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
174 | LOG.d(LOG_TAG, "Intent no connectivity: " + noConnectivity);
175 | if(noConnectivity) {
176 | LOG.d(LOG_TAG, "Really no connectivity");
177 | } else {
178 | LOG.d(LOG_TAG, "!!! Switching to unknown, Intent states there is a connectivity.");
179 | sendUpdate(TYPE_UNKNOWN);
180 | }
181 | }
182 | }
183 | };
184 | }
185 |
186 | webView.getContext().registerReceiver(this.receiver, intentFilter);
187 | }
188 |
189 | private void unregisterReceiver() {
190 | if (this.receiver != null) {
191 | try {
192 | webView.getContext().unregisterReceiver(this.receiver);
193 | } catch (Exception e) {
194 | LOG.e(LOG_TAG, "Error unregistering network receiver: " + e.getMessage(), e);
195 | } finally {
196 | receiver = null;
197 | }
198 | }
199 | }
200 |
201 | /**
202 | * Updates the JavaScript side whenever the connection changes
203 | *
204 | * @param info the current active network info
205 | * @return
206 | */
207 | private void updateConnectionInfo(NetworkInfo info) {
208 | // send update to javascript "navigator.connection"
209 | // Jellybean sends its own info
210 | String currentNetworkType = this.getTypeOfNetworkFallbackToTypeNoneIfNotConnected(info);
211 | if (currentNetworkType.equals(this.lastTypeOfNetwork)) {
212 | LOG.d(LOG_TAG, "Networkinfo state didn't change, there is no event propagated to the JavaScript side.");
213 | } else {
214 | sendUpdate(currentNetworkType);
215 | this.lastTypeOfNetwork = currentNetworkType;
216 | }
217 | }
218 |
219 | /**
220 | * Gets the type of network connection of the NetworkInfo input
221 | *
222 | * @param info the current active network info
223 | * @return type the type of network
224 | */
225 | private String getTypeOfNetworkFallbackToTypeNoneIfNotConnected(NetworkInfo info) {
226 | // the info might still be null in this part of the code
227 | String type;
228 | if (info != null) {
229 | // If we are not connected to any network set type to none
230 | if (!info.isConnected()) {
231 | type = TYPE_NONE;
232 | }
233 | else {
234 | type = getType(info);
235 | }
236 | } else {
237 | type = TYPE_NONE;
238 | }
239 |
240 | LOG.d(LOG_TAG, "Connection Type: " + type);
241 | return type;
242 | }
243 |
244 | /**
245 | * Create a new plugin result and send it back to JavaScript
246 | *
247 | * @param connection the network info to set as navigator.connection
248 | */
249 | private void sendUpdate(String type) {
250 | if (connectionCallbackContext != null) {
251 | PluginResult result = new PluginResult(PluginResult.Status.OK, type);
252 | result.setKeepCallback(true);
253 | connectionCallbackContext.sendPluginResult(result);
254 | }
255 | webView.postMessage("networkconnection", type);
256 | }
257 |
258 | /**
259 | * Determine the type of connection
260 | *
261 | * @param info the network info so we can determine connection type.
262 | * @return the type of mobile network we are on
263 | */
264 | private String getType(NetworkInfo info) {
265 | String type = info.getTypeName().toLowerCase(Locale.US);
266 |
267 | LOG.d(LOG_TAG, "toLower : " + type);
268 | if (type.equals(WIFI)) {
269 | return TYPE_WIFI;
270 | } else if (type.toLowerCase().equals(TYPE_ETHERNET) || type.toLowerCase().startsWith(TYPE_ETHERNET_SHORT)) {
271 | return TYPE_ETHERNET;
272 | } else if (type.equals(MOBILE) || type.equals(CELLULAR)) {
273 | type = info.getSubtypeName().toLowerCase(Locale.US);
274 | if (type.equals(GSM) ||
275 | type.equals(GPRS) ||
276 | type.equals(EDGE) ||
277 | type.equals(TWO_G)) {
278 | return TYPE_2G;
279 | } else if (type.startsWith(CDMA) ||
280 | type.equals(UMTS) ||
281 | type.equals(ONEXRTT) ||
282 | type.equals(EHRPD) ||
283 | type.equals(HSUPA) ||
284 | type.equals(HSDPA) ||
285 | type.equals(HSPA) ||
286 | type.equals(THREE_G)) {
287 | return TYPE_3G;
288 | } else if (type.equals(LTE) ||
289 | type.equals(UMB) ||
290 | type.equals(HSPA_PLUS) ||
291 | type.equals(FOUR_G)) {
292 | return TYPE_4G;
293 | }
294 | }
295 | return TYPE_UNKNOWN;
296 | }
297 | }
298 |
--------------------------------------------------------------------------------
/src/browser/network.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 |
21 | var cordova = require('cordova');
22 | var proxy = require('cordova/exec/proxy');
23 | var Connection = require('./Connection');
24 |
25 | var type = navigator.onLine ? Connection.UNKNOWN : Connection.NONE;
26 |
27 | // Subscribe to 'native' online/offline events
28 | function onStatusChange (evt) {
29 | type = navigator.onLine ? Connection.UNKNOWN : Connection.NONE;
30 | // force async
31 | setTimeout(function () {
32 | cordova.fireDocumentEvent(evt.type);
33 | }, 0);
34 | }
35 |
36 | window.addEventListener('online', onStatusChange);
37 | window.addEventListener('offline', onStatusChange);
38 |
39 | proxy.add('NetworkStatus', {
40 | getConnectionInfo: function (cbSuccess) {
41 | // force async
42 | setTimeout(function () {
43 | cbSuccess(type);
44 | }, 0);
45 | }
46 | });
47 |
--------------------------------------------------------------------------------
/src/ios/CDVConnection.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 "CDVReachability.h"
23 |
24 | @interface CDVConnection : CDVPlugin {
25 | NSString* type;
26 | NSString* _callbackId;
27 |
28 | CDVReachability* internetReach;
29 | }
30 |
31 | @property (copy) NSString* connectionType;
32 | @property (strong) CDVReachability* internetReach;
33 |
34 | @end
35 |
--------------------------------------------------------------------------------
/src/ios/CDVConnection.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 | #import
20 |
21 | #import "CDVConnection.h"
22 | #import "CDVReachability.h"
23 |
24 | @interface CDVConnection (PrivateMethods)
25 | - (void)updateOnlineStatus;
26 | - (void)sendPluginResult;
27 | @end
28 |
29 | @implementation CDVConnection
30 |
31 | @synthesize connectionType, internetReach;
32 |
33 | - (void)getConnectionInfo:(CDVInvokedUrlCommand*)command
34 | {
35 | _callbackId = command.callbackId;
36 | [self sendPluginResult];
37 | }
38 |
39 | - (void)sendPluginResult
40 | {
41 | CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:self.connectionType];
42 |
43 | [result setKeepCallbackAsBool:YES];
44 | [self.commandDelegate sendPluginResult:result callbackId:_callbackId];
45 | }
46 |
47 | - (NSString*)w3cConnectionTypeFor:(CDVReachability*)reachability
48 | {
49 | NetworkStatus networkStatus = [reachability currentReachabilityStatus];
50 |
51 | switch (networkStatus) {
52 | case NotReachable:
53 | return @"none";
54 |
55 | case ReachableViaWWAN:
56 | {
57 | BOOL isConnectionRequired = [reachability connectionRequired];
58 | if (isConnectionRequired) {
59 | return @"none";
60 | } else {
61 | if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0" options:NSNumericSearch] != NSOrderedAscending) {
62 | CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new];
63 | if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS]) {
64 | return @"2g";
65 | } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge]) {
66 | return @"2g";
67 | } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyWCDMA]) {
68 | return @"3g";
69 | } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSDPA]) {
70 | return @"3g";
71 | } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSUPA]) {
72 | return @"3g";
73 | } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
74 | return @"3g";
75 | } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]) {
76 | return @"3g";
77 | } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]) {
78 | return @"3g";
79 | } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]) {
80 | return @"3g";
81 | } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD]) {
82 | return @"3g";
83 | } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
84 | return @"4g";
85 | }
86 | }
87 | return @"cellular";
88 | }
89 | }
90 | case ReachableViaWiFi:
91 | {
92 | BOOL isConnectionRequired = [reachability connectionRequired];
93 | if (isConnectionRequired) {
94 | return @"none";
95 | } else {
96 | return @"wifi";
97 | }
98 | }
99 | default:
100 | return @"unknown";
101 | }
102 | }
103 |
104 | - (BOOL)isCellularConnection:(NSString*)theConnectionType
105 | {
106 | return [theConnectionType isEqualToString:@"2g"] ||
107 | [theConnectionType isEqualToString:@"3g"] ||
108 | [theConnectionType isEqualToString:@"4g"] ||
109 | [theConnectionType isEqualToString:@"cellular"];
110 | }
111 |
112 | - (void)updateReachability:(CDVReachability*)reachability
113 | {
114 | if (reachability) {
115 | // check whether the connection type has changed
116 | NSString* newConnectionType = [self w3cConnectionTypeFor:reachability];
117 | if ([newConnectionType isEqualToString:self.connectionType]) { // the same as before, remove dupes
118 | return;
119 | } else {
120 | self.connectionType = [self w3cConnectionTypeFor:reachability];
121 | }
122 | }
123 | [self sendPluginResult];
124 | }
125 |
126 | - (void)updateConnectionType:(NSNotification*)note
127 | {
128 | CDVReachability* curReach = [note object];
129 |
130 | if ((curReach != nil) && [curReach isKindOfClass:[CDVReachability class]]) {
131 | [self updateReachability:curReach];
132 | }
133 | }
134 |
135 | - (void)onPause
136 | {
137 | [self.internetReach stopNotifier];
138 | }
139 |
140 | - (void)onResume
141 | {
142 | [self.internetReach startNotifier];
143 | [self updateReachability:self.internetReach];
144 | }
145 |
146 | - (void)pluginInitialize
147 | {
148 | self.connectionType = @"none";
149 | self.internetReach = [CDVReachability reachabilityForInternetConnection];
150 | self.connectionType = [self w3cConnectionTypeFor:self.internetReach];
151 | [self.internetReach startNotifier];
152 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConnectionType:)
153 | name:kReachabilityChangedNotification object:nil];
154 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConnectionType:)
155 | name:CTRadioAccessTechnologyDidChangeNotification object:nil];
156 | if (UIApplicationDidEnterBackgroundNotification && UIApplicationWillEnterForegroundNotification) {
157 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil];
158 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil];
159 | }
160 | }
161 |
162 | @end
163 |
--------------------------------------------------------------------------------
/src/ios/CDVReachability.h:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | File: Reachability.h
4 | Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs.
5 | Version: 2.2
6 |
7 | Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
8 | ("Apple") in consideration of your agreement to the following terms, and your
9 | use, installation, modification or redistribution of this Apple software
10 | constitutes acceptance of these terms. If you do not agree with these terms,
11 | please do not use, install, modify or redistribute this Apple software.
12 |
13 | In consideration of your agreement to abide by the following terms, and subject
14 | to these terms, Apple grants you a personal, non-exclusive license, under
15 | Apple's copyrights in this original Apple software (the "Apple Software"), to
16 | use, reproduce, modify and redistribute the Apple Software, with or without
17 | modifications, in source and/or binary forms; provided that if you redistribute
18 | the Apple Software in its entirety and without modifications, you must retain
19 | this notice and the following text and disclaimers in all such redistributions
20 | of the Apple Software.
21 | Neither the name, trademarks, service marks or logos of Apple Inc. may be used
22 | to endorse or promote products derived from the Apple Software without specific
23 | prior written permission from Apple. Except as expressly stated in this notice,
24 | no other rights or licenses, express or implied, are granted by Apple herein,
25 | including but not limited to any patent rights that may be infringed by your
26 | derivative works or by other works in which the Apple Software may be
27 | incorporated.
28 |
29 | The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
30 | WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
31 | WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32 | PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
33 | COMBINATION WITH YOUR PRODUCTS.
34 |
35 | IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
36 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
37 | GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 | ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
39 | DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
40 | CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
41 | APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 |
43 | Copyright (C) 2010 Apple Inc. All Rights Reserved.
44 |
45 | */
46 |
47 | #import
48 | #import
49 | #import
50 |
51 | typedef enum {
52 | NotReachable = 0,
53 | ReachableViaWWAN, // this value has been swapped with ReachableViaWiFi for Cordova backwards compat. reasons
54 | ReachableViaWiFi // this value has been swapped with ReachableViaWWAN for Cordova backwards compat. reasons
55 | } NetworkStatus;
56 | #define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification"
57 |
58 | @interface CDVReachability : NSObject
59 | {
60 | SCNetworkReachabilityRef reachabilityRef;
61 | }
62 |
63 | // reachabilityWithHostName- Use to check the reachability of a particular host name.
64 | + (CDVReachability*)reachabilityWithHostName:(NSString*)hostName;
65 |
66 | // reachabilityWithAddress- Use to check the reachability of a particular IP address.
67 | + (CDVReachability*)reachabilityWithAddress:(const struct sockaddr*)hostAddress;
68 |
69 | // reachabilityForInternetConnection- checks whether the default route is available.
70 | // Should be used by applications that do not connect to a particular host
71 | + (CDVReachability*)reachabilityForInternetConnection;
72 |
73 | // Start listening for reachability notifications on the current run loop
74 | - (BOOL)startNotifier;
75 | - (void)stopNotifier;
76 |
77 | - (NetworkStatus)currentReachabilityStatus;
78 | // WWAN may be available, but not active until a connection has been established.
79 | // WiFi may require a connection for VPN on Demand.
80 | - (BOOL)connectionRequired;
81 | @end
82 |
--------------------------------------------------------------------------------
/src/ios/CDVReachability.m:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | File: Reachability.m
4 | Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs.
5 | Version: 2.2
6 |
7 | Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
8 | ("Apple") in consideration of your agreement to the following terms, and your
9 | use, installation, modification or redistribution of this Apple software
10 | constitutes acceptance of these terms. If you do not agree with these terms,
11 | please do not use, install, modify or redistribute this Apple software.
12 |
13 | In consideration of your agreement to abide by the following terms, and subject
14 | to these terms, Apple grants you a personal, non-exclusive license, under
15 | Apple's copyrights in this original Apple software (the "Apple Software"), to
16 | use, reproduce, modify and redistribute the Apple Software, with or without
17 | modifications, in source and/or binary forms; provided that if you redistribute
18 | the Apple Software in its entirety and without modifications, you must retain
19 | this notice and the following text and disclaimers in all such redistributions
20 | of the Apple Software.
21 | Neither the name, trademarks, service marks or logos of Apple Inc. may be used
22 | to endorse or promote products derived from the Apple Software without specific
23 | prior written permission from Apple. Except as expressly stated in this notice,
24 | no other rights or licenses, express or implied, are granted by Apple herein,
25 | including but not limited to any patent rights that may be infringed by your
26 | derivative works or by other works in which the Apple Software may be
27 | incorporated.
28 |
29 | The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
30 | WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
31 | WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32 | PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
33 | COMBINATION WITH YOUR PRODUCTS.
34 |
35 | IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
36 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
37 | GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 | ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
39 | DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
40 | CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
41 | APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 |
43 | Copyright (C) 2010 Apple Inc. All Rights Reserved.
44 |
45 | */
46 |
47 | #import
48 | #import
49 | #import
50 | #import
51 | #import
52 | #import
53 |
54 | #import
55 |
56 | #import "CDVReachability.h"
57 |
58 | #define kShouldPrintReachabilityFlags 0
59 |
60 | static void CDVPrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment)
61 | {
62 | #if kShouldPrintReachabilityFlags
63 | NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",
64 | (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
65 | (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-',
66 |
67 | (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',
68 | (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',
69 | (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',
70 | (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
71 | (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',
72 | (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',
73 | (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-',
74 | comment
75 | );
76 | #endif
77 | }
78 |
79 | @implementation CDVReachability
80 |
81 | static void CDVReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
82 | {
83 | #pragma unused (target, flags)
84 | // NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback");
85 | // NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback");
86 |
87 | // Converted the asserts above to conditionals, with safe return from the function
88 | if (info == NULL) {
89 | NSLog(@"info was NULL in ReachabilityCallback");
90 | return;
91 | }
92 |
93 | if (![(__bridge NSObject*)info isKindOfClass :[CDVReachability class]]) {
94 | NSLog(@"info was wrong class in ReachabilityCallback");
95 | return;
96 | }
97 |
98 | // We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively
99 | // in case someon uses the Reachability object in a different thread.
100 | @autoreleasepool {
101 | CDVReachability* noteObject = (__bridge CDVReachability*)info;
102 | // Post a notification to notify the client that the network reachability changed.
103 | [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:noteObject];
104 | }
105 | }
106 |
107 | - (BOOL)startNotifier
108 | {
109 | BOOL retVal = NO;
110 | SCNetworkReachabilityContext context = {0, (__bridge void*)(self), NULL, NULL, NULL};
111 |
112 | if (SCNetworkReachabilitySetCallback(reachabilityRef, CDVReachabilityCallback, &context)) {
113 | if (SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) {
114 | retVal = YES;
115 | }
116 | }
117 | return retVal;
118 | }
119 |
120 | - (void)stopNotifier
121 | {
122 | if (reachabilityRef != NULL) {
123 | SCNetworkReachabilitySetCallback(reachabilityRef, NULL, NULL);
124 | SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
125 | }
126 | }
127 |
128 | - (void)dealloc
129 | {
130 | [self stopNotifier];
131 | if (reachabilityRef != NULL) {
132 | CFRelease(reachabilityRef);
133 | }
134 | }
135 |
136 | + (CDVReachability*)reachabilityWithHostName:(NSString*)hostName;
137 | {
138 | CDVReachability* retVal = NULL;
139 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]);
140 | if (reachability != NULL) {
141 | retVal = [[self alloc] init];
142 | if (retVal != NULL) {
143 | retVal->reachabilityRef = reachability;
144 | }
145 | else {
146 | CFRelease(reachability);
147 | }
148 | }
149 | return retVal;
150 | }
151 |
152 | + (CDVReachability*)reachabilityWithAddress:(const struct sockaddr*)hostAddress;
153 | {
154 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, hostAddress);
155 | CDVReachability* retVal = NULL;
156 | if (reachability != NULL) {
157 | retVal = [[self alloc] init];
158 | if (retVal != NULL) {
159 | retVal->reachabilityRef = reachability;
160 | }
161 | else {
162 | CFRelease(reachability);
163 | }
164 | }
165 | return retVal;
166 | }
167 |
168 | // Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
169 | // status of the device, both IPv4 and IPv6.
170 | + (CDVReachability*)reachabilityForInternetConnection;
171 | {
172 | struct sockaddr_in zeroAddress;
173 | bzero(&zeroAddress, sizeof(zeroAddress));
174 | zeroAddress.sin_len = sizeof(zeroAddress);
175 | zeroAddress.sin_family = AF_INET;
176 | return [self reachabilityWithAddress:(const struct sockaddr*) &zeroAddress];
177 | }
178 |
179 | #pragma mark Network Flag Handling
180 |
181 | - (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags
182 | {
183 | CDVPrintReachabilityFlags(flags, "networkStatusForFlags");
184 | if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) {
185 | // if target host is not reachable
186 | return NotReachable;
187 | }
188 |
189 | NetworkStatus retVal = NotReachable;
190 |
191 | if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) {
192 | // if target host is reachable and no connection is required
193 | // then we'll assume (for now) that your on Wi-Fi
194 | retVal = ReachableViaWiFi;
195 | }
196 |
197 | if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0) ||
198 | ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))) {
199 | // ... and the connection is on-demand (or on-traffic) if the
200 | // calling application is using the CFSocketStream or higher APIs
201 |
202 | if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) {
203 | // ... and no [user] intervention is needed
204 | retVal = ReachableViaWiFi;
205 | }
206 | }
207 |
208 | if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
209 | // ... but WWAN connections are OK if the calling application
210 | // is using the CFNetwork (CFSocketStream?) APIs.
211 | retVal = ReachableViaWWAN;
212 | }
213 | return retVal;
214 | }
215 |
216 | - (BOOL)connectionRequired;
217 | {
218 | NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef");
219 | SCNetworkReachabilityFlags flags;
220 | if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) {
221 | return flags & kSCNetworkReachabilityFlagsConnectionRequired;
222 | }
223 | return NO;
224 | }
225 |
226 | - (NetworkStatus)currentReachabilityStatus
227 | {
228 | NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef");
229 | NetworkStatus retVal = NotReachable;
230 | SCNetworkReachabilityFlags flags;
231 | if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) {
232 | retVal = [self networkStatusForFlags:flags];
233 | }
234 | return retVal;
235 | }
236 |
237 | @end
238 |
--------------------------------------------------------------------------------
/src/windows/NetworkInfoProxy.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 | /* global Windows:true */
23 |
24 | var Connection = require('./Connection');
25 |
26 | var winNetConn = Windows.Networking.Connectivity;
27 | var networkInfo = winNetConn.NetworkInformation;
28 |
29 | function getCurrrentConnectionType () {
30 | var profile = networkInfo.getInternetConnectionProfile();
31 |
32 | if (!profile) {
33 | return Connection.NONE;
34 | }
35 |
36 | var conLevel = profile.getNetworkConnectivityLevel();
37 | var interfaceType = profile.networkAdapter.ianaInterfaceType;
38 |
39 | // since we use this to detect whether we are online or offline we do check agains InternetAccess
40 | // localAccess (airplane mode as an example) or constrainedInternetAccess mean there is no access to the internet available
41 | // https://msdn.microsoft.com/library/windows/apps/windows.networking.connectivity.networkconnectivitylevel.aspx
42 | if (conLevel !== Windows.Networking.Connectivity.NetworkConnectivityLevel.internetAccess) {
43 | return Connection.NONE;
44 | }
45 |
46 | var connectionType;
47 |
48 | switch (interfaceType) {
49 | case 71:
50 | connectionType = Connection.WIFI;
51 | break;
52 | case 6:
53 | connectionType = Connection.ETHERNET;
54 | break;
55 | case 243: // (3GPP WWAN) // Fallthrough is intentional
56 | case 244: // (3GPP2 WWAN)
57 | connectionType = Connection.CELL_3G;
58 | break;
59 | default:
60 | connectionType = Connection.UNKNOWN;
61 | break;
62 | }
63 |
64 | return connectionType;
65 | }
66 |
67 | module.exports = {
68 |
69 | getConnectionInfo: function (win, fail, args) {
70 | var reportConnectionInfoOnce = function () {
71 | win(getCurrrentConnectionType(), { keepCallback: true });
72 | };
73 |
74 | // report current connection type
75 | setTimeout(reportConnectionInfoOnce, 0);
76 | // start traking future changes
77 | networkInfo.addEventListener('networkstatuschanged', reportConnectionInfoOnce);
78 | }
79 | };
80 |
81 | require('cordova/exec/proxy').add('NetworkStatus', module.exports);
82 |
--------------------------------------------------------------------------------
/tests/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cordova-plugin-network-information-tests",
3 | "version": "3.0.1-dev",
4 | "description": "",
5 | "cordova": {
6 | "id": "cordova-plugin-network-information-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 |
25 | Cordova Network Information Plugin Tests
26 | Apache 2.0
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/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 | /* eslint-env jasmine */
23 | /* global Connection */
24 |
25 | exports.defineAutoTests = function () {
26 | describe('Network (navigator.connection)', function () {
27 | it('network.spec.1 should exist', function () {
28 | expect(navigator.connection).toBeDefined();
29 | });
30 |
31 | it('network.spec.2 should be set to a valid value', function () {
32 | var validValues = {
33 | unknown: 1,
34 | ethernet: 1,
35 | wifi: 1,
36 | '2g': 1,
37 | cellular: 1,
38 | '3g': 1,
39 | '4g': 1,
40 | none: 1
41 | };
42 | expect(validValues[navigator.connection.type]).toBe(1);
43 | });
44 |
45 | it('network.spec.4 should define constants for connection status', function () {
46 | expect(Connection.UNKNOWN).toBe('unknown');
47 | expect(Connection.ETHERNET).toBe('ethernet');
48 | expect(Connection.WIFI).toBe('wifi');
49 | expect(Connection.CELL_2G).toBe('2g');
50 | expect(Connection.CELL_3G).toBe('3g');
51 | expect(Connection.CELL_4G).toBe('4g');
52 | expect(Connection.NONE).toBe('none');
53 | expect(Connection.CELL).toBe('cellular');
54 | });
55 | });
56 | };
57 |
58 | /******************************************************************************/
59 | /******************************************************************************/
60 | /******************************************************************************/
61 |
62 | exports.defineManualTests = function (contentEl, createActionButton) {
63 | function eventOutput (s) {
64 | var el = document.getElementById('results');
65 | el.innerHTML = el.innerHTML + s + '
';
66 | }
67 |
68 | function printNetwork () {
69 | eventOutput('navigator.connection.type=' + navigator.connection.type);
70 | }
71 |
72 | function onEvent (e) {
73 | eventOutput('Event of type: ' + e.type);
74 | printNetwork();
75 | }
76 |
77 | /******************************************************************************/
78 |
79 | var html = '' +
80 | 'Results:
' +
81 | '' +
82 | '
' +
83 | 'Expected result: Status box will update with type of connection using two different methods. Both values must match.' +
84 | ' The result will be unknown, ethernet, wifi, 2g, 3g, 4g, none, or cellular. Make sure it matches what the device is connected to.' +
85 | '
';
86 |
87 | document.addEventListener('online', onEvent, false);
88 | document.addEventListener('offline', onEvent, false);
89 | contentEl.innerHTML = html;
90 |
91 | createActionButton('Show Network Connection', function () {
92 | printNetwork();
93 | }, 'connection');
94 |
95 | createActionButton('Clear Log', function () {
96 | document.getElementById('results').innerHTML = '';
97 | }, 'actions');
98 | };
99 |
--------------------------------------------------------------------------------
/types/index.d.ts:
--------------------------------------------------------------------------------
1 | // Type definitions for Apache Cordova Network Information plugin
2 | // Project: https://github.com/apache/cordova-plugin-network-information
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 |
9 | interface Navigator {
10 | /**
11 | * This plugin provides an implementation of an old version of the Network Information API.
12 | * It provides information about the device's cellular and wifi connection, and whether the device has an internet connection.
13 | */
14 | connection: Connection;
15 | // see https://github.com/apache/cordova-plugin-network-information/blob/dev/doc/index.md#api-change
16 | // for
17 | network: {
18 | /**
19 | * This plugin provides an implementation of an old version of the Network Information API.
20 | * It provides information about the device's cellular and wifi connection, and whether the device has an internet connection.
21 | */
22 | connection: Connection
23 | }
24 | }
25 |
26 | interface Document {
27 | addEventListener(type: "online", connectionStateCallback: () => any, useCapture?: boolean): void;
28 | addEventListener(type: "offline", connectionStateCallback: () => any, useCapture?: boolean): void;
29 | }
30 |
31 | /**
32 | * The connection object, exposed via navigator.connection, provides information
33 | * about the device's cellular and wifi connection.
34 | */
35 | interface Connection {
36 | /**
37 | * This property offers a fast way to determine the device's network connection state, and type of connection.
38 | * One of:
39 | * Connection.UNKNOWN
40 | * Connection.ETHERNET
41 | * Connection.WIFI
42 | * Connection.CELL_2G
43 | * Connection.CELL_3G
44 | * Connection.CELL_4G
45 | * Connection.CELL
46 | * Connection.NONE
47 | */
48 | type: string;
49 | addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
50 | removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
51 | }
52 |
53 | declare var Connection: {
54 | UNKNOWN: string;
55 | ETHERNET: string;
56 | WIFI: string;
57 | CELL_2G: string;
58 | CELL_3G: string;
59 | CELL_4G: string;
60 | CELL: string;
61 | NONE: string;
62 | }
--------------------------------------------------------------------------------
/www/Connection.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 | /**
23 | * Network status
24 | */
25 | module.exports = {
26 | UNKNOWN: 'unknown',
27 | ETHERNET: 'ethernet',
28 | WIFI: 'wifi',
29 | CELL_2G: '2g',
30 | CELL_3G: '3g',
31 | CELL_4G: '4g',
32 | CELL: 'cellular',
33 | NONE: 'none'
34 | };
35 |
--------------------------------------------------------------------------------
/www/network.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 |
21 | var exec = require('cordova/exec');
22 | var cordova = require('cordova');
23 | var channel = require('cordova/channel');
24 | var utils = require('cordova/utils');
25 |
26 | // Link the onLine property with the Cordova-supplied network info.
27 | // This works because we clobber the navigator object with our own
28 | // object in bootstrap.js.
29 | // Browser platform do not need to define this property, because
30 | // it is already supported by modern browsers
31 | if (cordova.platformId !== 'browser' && typeof navigator !== 'undefined') {
32 | utils.defineGetter(navigator, 'onLine', function () {
33 | return this.connection.type !== 'none';
34 | });
35 | }
36 |
37 | function NetworkConnection () {
38 | this.type = 'unknown';
39 | }
40 |
41 | /**
42 | * Get connection info
43 | *
44 | * @param {Function} successCallback The function to call when the Connection data is available
45 | * @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL)
46 | */
47 | NetworkConnection.prototype.getInfo = function (successCallback, errorCallback) {
48 | exec(successCallback, errorCallback, 'NetworkStatus', 'getConnectionInfo', []);
49 | };
50 |
51 | var me = new NetworkConnection();
52 | var timerId = null;
53 | var timeout = 500;
54 |
55 | channel.createSticky('onCordovaConnectionReady');
56 | channel.waitForInitialization('onCordovaConnectionReady');
57 |
58 | channel.onCordovaReady.subscribe(function () {
59 | me.getInfo(function (info) {
60 | me.type = info;
61 | if (info === 'none') {
62 | // set a timer if still offline at the end of timer send the offline event
63 | timerId = setTimeout(function () {
64 | cordova.fireDocumentEvent('offline');
65 | timerId = null;
66 | }, timeout);
67 | } else {
68 | // If there is a current offline event pending clear it
69 | if (timerId !== null) {
70 | clearTimeout(timerId);
71 | timerId = null;
72 | }
73 | cordova.fireDocumentEvent('online');
74 | }
75 |
76 | // should only fire this once
77 | if (channel.onCordovaConnectionReady.state !== 2) {
78 | channel.onCordovaConnectionReady.fire();
79 | }
80 | },
81 | function (e) {
82 | // If we can't get the network info we should still tell Cordova
83 | // to fire the deviceready event.
84 | if (channel.onCordovaConnectionReady.state !== 2) {
85 | channel.onCordovaConnectionReady.fire();
86 | }
87 | console.log('Error initializing Network Connection: ' + e);
88 | });
89 | });
90 |
91 | module.exports = me;
92 |
--------------------------------------------------------------------------------