An error has occurred: The object 'navigator.connection.type' is not defined (evaluating 'navigator.connection.type')

I am currently in the process of developing a Cordova app and utilizing the Cordova network-information plugin org.apache.cordova.network-information. Lately, I have been encountering an unusual bug when debugging in Safari's web inspector that reads "TypeError 'undefined' is not an object (evaluating 'navigator.connection.type')". The app functions properly during the initial load, but upon further navigation within the app, this error appears and causes the app to freeze. This issue seems to be more prevalent in iOS 8 compared to Android Lollipop where it occurs sporadically. Despite trying various suggestions and resources related to this problem, I have not been able to find a solution. My setup includes Cordova version 4.3 and iOS 8.1. Any assistance on resolving this would be greatly appreciated. Apologies for being unable to provide images due to insufficient reputation.

function checkConnection() { 
    alert(navigator.connection.type);
    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';
    if(networkState == Connection.UNKNOWN || networkState == Connection.NONE){
        navigator.notification.alert('No Network Available',null,"Warning");
        sessionStorage.setItem('UserID',"");
        $.mobile.changePage("#loginPage", {
                            transition: 'none',
                            showLoadMsg: true
                            });
        return false;
    }else{
        return true;
   }
}

Answer №1

The issue I encountered was related to incorrectly calling the function outside of the device ready event handler. To resolve this, I made the following adjustment:

document.addEventListener("deviceready", function(){
     // Implement your navigator.connection.type logic here 
    }, false);

Answer №2

Make sure that you have properly defined the following:

<feature name="NetworkStatus">
         <param name="android-package" value="CDVConnection" />
 </feature>

The feature name should be 'Network status' and the value should be your class name.

Also, in the Android Manifest file, include the following permission:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Don't forget to check cordova_plugin.js for the necessary configurations:

cordova.define('cordova/plugin_list', function (require, exports, module) {
    module.exports = [{
        "file": "plugins/org.apache.cordova.dialogs/www/notification.js",
        "id": "org.apache.cordova.dialogs.notification",
        "merges": ["navigator.notification"]
    }, {
        "file": "plugins/org.apache.cordova.network-information/www/network.js",
        "id": "org.apache.cordova.network-information.network",
        "clobbers": ["navigator.connection", "navigator.network.connection"]
    }];
    module.exports.metadata = // TOP OF METADATA 
    {
        "org.apache.cordova.device": "0.2.8",
        "org.apache.cordova.network-information": "0.2.7"
    }
});

Answer №3

I encountered a similar issue while using cordova-plugin-network-information. I observed that even though the function was being called after "deviceready" event, the navigator.connection.type object remained undefined. To work around this, I introduced a 200ms delay before accessing the object.

function checkConnection(){
    try{
        console.log(navigator.connection.type);
    }
    catch(e){
        alert("error : "+e);
    }

    setTimeout(function(){
        var networkState = navigator.connection.type;
        console.log(networkState);

        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]);
        if(states[networkState] == "No network connection"){
            window.location.assign("lostConnection.html");
        }
    }, 200);
}

Initially, the "try/catch" block may encounter errors due to the undefined object, but eventually, after a short delay, retrieving navigator.connection.type succeeds. At least it did for me!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js error message: Unable to load HTTP module

Recently starting with Node.js, I decided to install the latest version (4.2.1) on my Windows 7 PC. However, when trying to include the HTTP module by writing: var http = require("http"); I'm receiving an undefined error message. Can someone help me ...

Understanding Gradle's BuildConfigFields Syntax

Could the syntax be the issue here? I keep getting the error message 'Gradle DSL method not found: buildConfigFields()'. android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.okason.dra ...

How can you display two images by hovering your mouse over them?

I am attempting to create a header that resembles the one found at . I am curious about how they were able to make it flash when hovering over the home button. I understand that two images are required for this effect, but I am unsure of the specific func ...

Calculate the sum in real-time using JavaScript

How can I dynamically compute the sum of subtotals without encountering the following error? document.getElementById("item_subtotal[" + cnt + "]") is null Below is my JavaScript code: function calculateTotalAll(numitems) { var cnt = 1; var tot ...

Ultimate 2022 Android handbook for saving data to filesDir in MVVM repository

My goal is to write a JSON file to internal storage while following the MVVM architecture. However, it has been challenging to find resources that focus on this specific task. Most information online pertains to external storage or databases, and very litt ...

Determine the position of an item in an array specified by the user

There is an EditText field that enables users to input items. `EditText editText = (EditText) findViewById(R.id.edit); String s = editText.getText().toString(); String [] array = s.split("\");` If a user enters D\A\E\B, and now I ne ...

Steps for turning off the browser's postback warning dialog

Currently, I am working on an ASP.NET application that is designed to work solely on IE7 for our internal website. One issue I have encountered is when a user needs to input data, a child window with a form pops up. After the form is closed, I have implem ...

Shuffled NSMutableArray elements were inserted into a different NSMutableArray in a mixed-up fashion

I currently have a NSMutableArray containing 100 elements. I am looking to extract "20 - 50", "10 - 20", "60 - 100" and 50 - 60. elements into separate NSMutableArrays, as well as their corresponding index values into another NSMutableArray. Is there a m ...

preclude any dates prior to the chosen date

I need a solution for a scenario where I have 5 datepickers in sequence. When I select a date on the first picker, all previous dates should be disabled when selecting on the next picker. Additionally, once a date is selected on one picker, the following ...

Rotating arrows enhance the functionality of the accordion menu

I have successfully implemented a basic accordion with rotating arrows on click. Everything is working smoothly except for one issue: When I collapse one item and then try to collapse another, the previous arrow does not return to its default state. Is ...

The functionality of the <select-vue> component in Vue.js does not support null values

custom-select.vue <template> <div class="relative"> <label :for="$attrs.name" class="block text-sm font-medium leading-6 text-gray-900" >{{ $t($attrs.label) }} {{ required ? '*&ap ...

Include the «Load More» option in the data output retrieved using $.getJSON from a Google Spreadsheet

Utilizing Google Spreadsheets as a "Backend", I retrieve the spreadsheet data through Google's JSON-Output () using jQuery's $.getJSON(), process the data by adding values to arrays, and then display the content on the frontend by iterating throu ...

Creating a JavaScript function to download specific sections of an HTML page

Currently, I am implementing PHP MySQL in my HTML page. I have already utilized several div elements in my page. I successfully created a print button that prints a specific div on the page. Now, I am looking to add a download button that will allow users ...

The webpage is completely blank, displaying only a stark white screen

After designing a website, I encountered an issue where upon opening it in the browser, it only shows a blank white page. I am puzzled as to why this is happening. Could you please take a look at this link and assist me? Thank you in advance. ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Using express to efficiently redirect from a search form?

As a newcomer to this, my goal is to initiate an external API call after entering a term in a search form and then migrating to a new page displaying the outcomes. Here's what I have accomplished thus far. const express = require('express') ...

At which location do you configure the applicationIconBadgeNumber?

Can anyone guide me on how to set up the applicationIconBadgeNumber for a React Native / Expo application on both iOS and Android platforms? I am currently using React Native, Visual Studio Code, and Expo. Where should I look to configure this feature? O ...

Bring about a transformation in the background color of a form upon losing focus after inputting text

Just to clarify, everything here is client side and not web-based at all. My goal is to change the form boxes to green after losing focus when text has been inputted. The form boxes initially start out white, turn purple on focus, and I want them to turn ...

Guide to using JavaScript to populate the dropdown list in ASP

On my aspx page, I have an ASP list box that I need to manually populate using external JavaScript. How can I access the list box in JavaScript without using jQuery? I am adding the JavaScript to the aspx page dynamically and not using any include or impor ...

ASP.NET Core does not support jQuery.validate functionality

After successfully creating a functional jQuery.validation form using HTML, CSS, and JS with dependencies like jQuery and Validation, I encountered an issue when implementing the same code in a clean ASP.NET Core web project. It seems that my custom valida ...