Error encountered: Cordova plugins return undefined values when testing on an actual device

I am currently utilizing Phonegap in conjunction with ngCordova and AngularJS. The aim is to leverage the capabilities of the plugin (PhoneGap-Image-Resizer) to facilitate media saving on the device. However, I encountered an issue where the plugin throws the following error:

[phonegap] [console.error] Error: undefined is not an object (evaluating '$window.imageResizer.getImageSize')

This problem only surfaces when testing the application on the device itself; no error occurs when running it locally via localhost:3000. Similar issues arise when performing a console log post DeviceReady call—on the browser everything functions normally, whereas on the device it returns as undefined.

Following extensive research, some sources suggest checking whether the cordova.js file is properly referenced in my index.html file, which indeed seems to be done correctly:

Index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <link rel="stylesheet" type="text/css" href="css/app.css" />
</head>

<body class="app-container">
    <div class="app">
      <div ng-app="MyApp" class="ui-view-container">
        <ui-view class="main-view">
        <img src="/img/logo.png" alt="my App" class="loading-logo"/>
        </ui-view>
        </div>
    </div>

    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript" src="js/angular-route.js"></script>
    <script type="text/javascript" src="js/angular-touch.js"></script>
    <script type="text/javascript" src="js/angular-animate.min.js"></script>
    <script type="text/javascript" src="js/angular-ui-router.min.js"></script>
    <script type="text/javascript" src="js/angular-foundation.js"></script>
    <script type="text/javascript" src="js/angular-modules/app.js"></script>
    <script type="text/javascript" src="js/angular-modules/controllers/main.js"></script>
    <script type="text/javascript" src="js/ng-cordova.js"></script>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript">
        app.initialize();
    </script>
</body>

</html>

Below is an excerpt from my partial:

<div class="row collapse expanded text-center camera">
    <div class="row">
        <div class="small-12 columns end">
            <canvas id="canvas" height="250" width="375"></canvas>
        </div>
    </div>

    <div class="row">

    <div class="small-12 columns">
    <h2>Image of canvas</h2>
            <img id="CanvasImage" alt="text" /> 
        </div>
    </div>

    <div class="row">
        <div class="small-6 columns">
            <a class="button expanded" ng-click="camera()">Camera</a>
        </div>
        <div class="small-6 columns">
            <a class="button expanded" ng-click="savecanvas()">savecanvas</a>
        </div>
    </div>
</div>

Here is the specifics within my controller:

angular.module('MyApp')
    .controller('CameraCtrl', function($scope, $cordovaCamera, $rootScope, $location, $window, starFactory) {

        $scope.savecanvas = function() {
            document.addEventListener("deviceready", function() {
                var theCanvas = document.getElementById('canvas');
                var CanvasImage = document.getElementById('CanvasImage');
                CanvasImage.src = theCanvas.toDataURL("image/png");

                $window.imageResizer.storeImage(
                    function(data) { console.log('It worked!');}, 
                    function (error) {console.log("Error : \r\n" + error);}, 
                    theCanvas.toDataURL("image/png"),
                    {imageDataType: ImageResizer.IMAGE_DATA_TYPE_BASE64,format: ImageResizer.FORMAT_JPG}
                );

            }, false);
        };


    });

If anyone has insight on why the plugins return as undefined while operating on the device as opposed to functioning correctly on the browser, any assistance or guidance would be greatly appreciated.

Answer №1

Are you extracting the data URL from the canvas as a PNG and then attempting to save it as a jpg?

You might want to consider using this code instead:

theCanvas.toDataURL("image/jpeg", 1);

As opposed to the original method:

theCanvas.toDataURL("image/png");

Answer №2

After delving into the Git-hub, I came across a plugin that caught my interest. In the Android quirks and howto's section, it explicitly states that the storeImage function will consistently save the image to the device's default external storage, using the specified Directory and filename. The photoAlbum property is rendered obsolete in this scenario. It appears that having an external memory card on your mobile device is imperative for this process to work seamlessly.

Answer №3

Figuring this out was quite challenging, but after some persistence, we finally uncovered the solution. Phonegap utilizes a feature called Hydration, which allows for updating an application without requiring a full reinstallation each time. However, there appears to be a bug in Hydration within Phonegap version 6.5.0 that causes the cordova.js file not to load correctly. The workaround for this issue is to disable Hydration. Once I disabled it, the plugins successfully loaded on the device.

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

A technique in JavaScript that allows for assigning object property values using an external variable

I need to clarify my situation with a code example const faultLine = new google.maps.Polyline({ paths: [ new google.maps.LatLng(49.95, -128.1), new google.maps.LatLng(46.26, -126.3), new google.maps.LatLng(40.3, -125.4) ] }); ...

Guide on adjusting the resolution/density of images in JPEG/PNG using JavaScript

I am looking for a way to adjust the resolution/density of JPG/PNG images using JavaScript. The purpose of this adjustment is to provide accurate metadata on the number of pixels per inch (DPI/PPI) to be used for printing by a third-party API. Is there a ...

An issue has arisen when trying to fetch and parse data using React and JavaScript

I am currently facing some challenges with fetching data from an API and displaying it using React. I have encountered errors and I am struggling with parsing the JSON response from the API. I believe that converting the response into an array may help res ...

The jQuery UI Dialog is experiencing an issue with a button that is triggering a HierarchyRequest

I am facing an issue with a piece of javascript that works perfectly on other pages but is now throwing a HierarchyRequestError on a new page. This leads me to believe that there may be an HTML problem on this particular page. Here is a simplified version ...

Transforming an array of strings into an array: a guide

An API call is returning an object with the following structure: data = { ... filter: "[1,2,3]" ... } I need to convert the string of array into an actual array of numbers, like [1,2,3]. Thank you! ...

Updating the value of a key within a jQuery object

A custom modal plugin has been developed with options that can be set by default or by the user. These values are passed to a function for updating, and it is desired that the options object as a whole is updated rather than individual values. The user&ap ...

Expo: A guide on integrating expo code into an existing Android project

I'm looking to enhance my Android app (which is built in standard Java) by allowing users to create their own 3D models. To achieve this, I want to incorporate a 3D viewer within the app so that users can view and interact with their creations. My pl ...

Neglecting the error message for type assignment in the Typescript compiler

Presented here is a scenario I am facing: const customer = new Customer(); let customerViewModel = new CustomerLayoutViewModel(); customerViewModel = customer; Despite both Customer and CustomerLayoutViewModel being identical at the moment, there is no ...

Changing global properties in VueCli

Recently, I integrated a component library into my Vue 3 project. All instances of the component require the same styles. Instead of manually adjusting each instance's props, I opted to utilize a global property: app.config.globalProperties.$tooltipS ...

Can a link be generated that swaps out the original URL redirect for the following visitor upon clicking?

Can the program be fed with a list of links to automatically redirect to the next URL once clicked? In this setup, each visitor would only see one link and not have access to any other URLs in the chain. Is there a way to make this happen? Any suggestion ...

Tips for Accessing a New Website Using the Floating Layer Close Button

How can I trigger the opening of a new browser window when a visitor clicks the close "x" on my floating layer ad? The close button is within an HTML link code ("a href"), but simply putting a URL in there does not seem to work. <script language=" ...

Utilizing AngularJS: Binding stateParams value to custom data within state objects

Following the guidelines here, I am setting a page title in my state object. $stateProvider .state('project', { url: '/projects/:origin/:owner/:name', template: '<project></project>', data : { pageTi ...

Tips for updating the URL and refreshing the page in Safari and Firefox

I am facing an issue with my ajax call that is written in jQuery. It sends a string to the server and receives back some json data. $.ajax({ url: ..., dataType: 'json', success: function(data) { for (var d in ...

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

Are Ajax Caching and Proper Format Being Employed?

Can you help me with a JavaScript event that I have to call in this way: function addEvent(date, resId) { $("#appPlaceholder").load("/Schedule/Add?date=" + date.format()+"&resourceId="+resId, function () { $('#event ...

"Exploring the integration of video.js with React Hooks: A step-by-step

I have been utilizing video.js within the React framework and am now looking to transition to React Hooks. The current version of my React project is 16.8.3 Below is the initial functioning code: import React, { PureComponent } from 'react'; i ...

Guide to utilizing Terser in conjunction with webpack

I am currently using Webpack 6.10.2 in combination with Vue 3.9.3. I encountered an issue with Uglify.js when running npm run build due to its inability to handle ES6 code. To work around this problem, I followed the recommendation of removing Uglify fro ...

Utilizing the scrollTop method to display the number of pixels scrolled on

My goal is to show the number of pixels a user has scrolled on my website using the scrollTop method in jQuery. I want this number of pixels to be displayed within a 'pixels' class. Therefore, I plan to have <p><span class="pixels"> ...

Creating an Angular directive that handles asynchronous attribute interpolation

I am facing an issue with my custom directive. In the link function attributes, I am trying to access the value of attributes.user. Here is how the directive is used in my view page: <div my-directive user="{{user.name}}"></div> The user obje ...

Is there a way for me to determine the size of this JSON structure?

Can anyone help me figure out the length of this JSON object? I need to know how many data are in it. var ddData = [{ "01":"United States", "02":"United Kingdom", "03":"Aruba", "04":"United Kingdom", ...