aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/network_information_api/index.html
blob: 38951b5d1a7691713260f9413bed5aae9d774ef3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
---
title: 网络状况 API
slug: Web/API/Network_Information_API
translation_of: Web/API/Network_Information_API
---
<div>{{SeeCompatTable}}</div>

<p>网络状态 API 可以获取到系统的网络连接信息,比如说连接方式是 WiFi 还是蜂窝。应用程序可以根据此信息为用户展现不同清晰度的内容。该 API 是由 {{domxref("NetworkInformation")}} 接口和 {{domxref("Navigator")}} 接口上新增的一个 {{domxref("Navigator.connection", "connection")}} 属性组成的。</p>

<h2 id="侦测连接状态变化">侦测连接状态变化</h2>

<p>下面是一个侦测用户设备连接状态变化的例子。</p>

<pre class="brush: js">var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
var type = connection.type;

function updateConnectionStatus() {
  console.log("设备的网络连接从" + type + "变成了" + connection.type);
}

connection.addEventListener('change', updateConnectionStatus);
</pre>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('Network Information', '', 'Network Information API')}}</td>
   <td>{{Spec2('Network Information')}}</td>
   <td>Initial specification</td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<p>{{CompatibilityTable}}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>Firefox OS</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>2.2 {{property_prefix("webkit")}}</td>
   <td>12.0<sup>[1]</sup></td>
   <td>1.4</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<p>[1] 在 Firefox 中,网络状况 API 可以通过 <code>dom.netinfo.enabled</code> 偏好选项来控制开启与否。</p>

<h2 id="相关链接">相关链接</h2>

<ul>
 <li>{{spec("http://w3c.github.io/netinfo/", "Network Information API Specification", "ED")}}</li>
 <li><a href="/en-US/docs/Online_and_offline_events">Online and offline events</a></li>
 <li>{{domxref("window.navigator.connection")}}</li>
</ul>