--- 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>