cordova-plugin-network-information

Android Testsuite Chrome Testsuite iOS Testsuite Lint Test

這個外掛提供舊版本的 網路資訊 API 的實作。它提供裝置的行動網路和 Wi-Fi 連線資訊,以及裝置是否連線到網際網路。

要了解如何使用這個外掛的一些想法,請查看此頁面底部的範例,或直接跳到參考內容。

安裝

cordova plugin add cordova-plugin-network-information

支援的平台

  • Android
  • 瀏覽器
  • iOS
  • Windows

連線

透過 navigator.connection 公開的 connection 物件,提供裝置的行動網路和 Wi-Fi 連線資訊。

屬性

  • connection.type

常數

  • Connection.UNKNOWN
  • Connection.ETHERNET
  • Connection.WIFI
  • Connection.CELL_2G
  • Connection.CELL_3G
  • Connection.CELL_4G
  • Connection.CELL
  • Connection.NONE

connection.type

此屬性提供一種快速判斷裝置網路連線狀態和連線類型的方法。

快速範例

function checkConnection() {
    var networkState = navigator.connection.type;

    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.CELL]     = 'Cell generic connection';
    states[Connection.NONE]     = 'No network connection';

    alert('Connection type: ' + states[networkState]);
}

checkConnection();

iOS 的注意事項

  • iOS7 無法偵測行動網路連線的類型。
    • 針對所有行動數據,navigator.connection.type 都設定為 Connection.CELL

Windows 的注意事項

  • 在 Phone 8.1 模擬器中執行時,navigator.connection.type 一律偵測為 Connection.ETHERNET

瀏覽器的注意事項

  • 瀏覽器無法偵測網路連線的類型。連線時,navigator.connection.type 一律設定為 Connection.UNKNOWN

與網路相關的事件

offline

當應用程式離線且裝置未連線到網際網路時,會觸發此事件。

document.addEventListener("offline", yourCallbackFunction, false);

詳細資訊

當先前連線的裝置失去網路連線,導致應用程式無法再存取網際網路時,會觸發 offline 事件。它依賴與連線 API 相同的資訊,並在 connection.type 的值變為 NONE 時觸發。

應用程式通常應使用 document.addEventListenerdeviceready 事件觸發後附加事件監聽器。

快速範例

document.addEventListener("offline", onOffline, false);

function onOffline() {
    // Handle the offline event
}

注意事項

此外掛程式在背景時無法廣播事件。請改用 navigator.connection.typeresume 事件中檢查連線狀態。

iOS 的注意事項

在初始啟動期間,第一個離線事件(如果適用)至少需要一秒才能觸發。

online

當應用程式上線且裝置連線到網際網路時,會觸發此事件。

document.addEventListener("online", yourCallbackFunction, false);

詳細資訊

當先前未連線的裝置收到網路連線,允許應用程式存取網際網路時,會觸發 online 事件。它依賴與連線 API 相同的資訊,並在 connection.typeNONE 變為任何其他值時觸發。

應用程式通常應使用 document.addEventListenerdeviceready 事件觸發後附加事件監聽器。

快速範例

document.addEventListener("online", onOnline, false);

function onOnline() {
    // Handle the online event
}

注意事項

此外掛程式在背景時無法廣播事件。請改用 navigator.connection.typeresume 事件中檢查連線狀態。

iOS 的注意事項

在初始啟動期間,第一個 online 事件(如果適用)至少需要一秒才能觸發,在此之前 connection.typeUNKNOWN

範例:根據網路狀態上傳檔案

此區段中的程式碼範例顯示使用線上和離線事件以及您的網路連線狀態來變更應用程式行為的範例。

首先,建立一個新的 FileEntry 物件 (data.txt) 來使用範例資料。從 deviceready 處理常式呼叫此函式。

注意 此程式碼範例需要 File 外掛。

var dataFileEntry;

function createSomeData() {

    window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {

        console.log('file system open: ' + fs.name);
        // Creates a new file or returns an existing file.
        fs.root.getFile("data.txt", { create: true, exclusive: false }, function (fileEntry) {

          dataFileEntry = fileEntry;

        }, onErrorCreateFile);

    }, onErrorLoadFs);
}

接下來,在 deviceready 處理常式中新增線上和離線事件的監聽器。

document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);

應用程式的 onOnline 函式會處理線上事件。在事件處理常式中,檢查目前的網路狀態。在此應用程式中,除了 Connection.NONE 之外,將任何連線類型都視為良好。如果您有連線,您會嘗試上傳檔案。

function onOnline() {
    // Handle the online event
    var networkState = navigator.connection.type;

    if (networkState !== Connection.NONE) {
        if (dataFileEntry) {
            tryToUploadFile();
        }
    }
    display('Connection type: ' + networkState);
}

當前面的程式碼觸發線上事件時,請呼叫應用程式的 tryToUploadFile 函式。

如果上傳失敗,則呼叫應用程式的 offlineWrite 函式將目前資料儲存到某處。

注意 為簡化起見,省略了檔案讀取和寫入。有關檔案處理的更多資訊,請參閱 cordova-plugin-file 文件。

function tryToUploadFile() {
    // !! Assumes variable fileURL contains a valid URL to a text file on the device,
    var fileURL = getDataFileEntry().toURL();
    
    getFileBlobSomehow(fileURL, function(fileBlob) {
        var success = function (r) {
            console.log("Response = " + r.response);
            display("Uploaded. Response: " + r.response);
        };

        var fail = function (error) {
            console.log("An error has occurred: Code = " + error.code || error.status);
            offlineWrite("Failed to upload: some offline data");
        }

        var xhr = new XMLHttpRequest();

        xhr.onerror = fail;
        xhr.ontimeout = fail;
        xhr.onload = function() {
            // If the response code was successful...
            if (xhr.status >= 200 && xhr.status < 400) {
                success(xhr);
            }
            else {
                fail(xhr)
            }
        }

        // Make sure you add the domain of your server URL to the
        // Content-Security-Policy <meta> element in index.html.
        xhr.open("POST", encodeURI(SERVER));

        xhr.setRequestHeader("Content-Type", "text/plain");

        // The server request handler could read this header to
        // set the filename.
        xhr.setRequestHeader("X-Filename", fileURL.substr(fileURL.lastIndexOf("/") + 1));

        xhr.send(fileBlob);
    });
};

以下是 offlineWrite 函式的程式碼。

注意 此程式碼範例需要 File 外掛。

function offlineWrite(offlineData) {
    // Create a FileWriter object for our FileEntry.
    dataFileEntry.createWriter(function (fileWriter) {

        fileWriter.onwriteend = function () {
            console.log("Successful file write...");
            display(offlineData);
        };

        fileWriter.onerror = function (e) {
            console.log("Failed file write: " + e.toString());
        };

        fileWriter.write(offlineData);
    });
}

如果發生離線事件,只需執行一些操作(例如通知使用者)(對於此範例,只需記錄它)。

function onOffline() {
    // Handle the offline event
    console.log("lost connection");
}