Phonegap Cordova 3.0.0 navigator.camera is undefined

旧巷老猫 提交于 2019-11-28 08:01:32

问题


I'm trying to use the Cordova native plugins for the first time. I started out with the camera and the sample code provided in the documentation. This is failing however and the navigator.camera is undefined.

I've included the code below.

<div data-role="page" id="CameraPage">
<script type="text/javascript" charset="utf-8">

var pictureSource;   // picture source
var destinationType; // sets the format of returned value

// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);

// device APIs are available
//
function onDeviceReady() {
    pictureSource=navigator.camera.PictureSourceType;
    destinationType=navigator.camera.DestinationType;
}

// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
  alert("Photo Data Success");
  // Uncomment to view the base64-encoded image data
  // console.log(imageData);

  // Get image handle
  //
  var smallImage = document.getElementById('smallImage');

  // Unhide image elements
  //
  smallImage.style.display = 'block';

  // Show the captured photo
  // The inline CSS rules are used to resize the image
  //
  smallImage.src = "data:image/jpeg;base64," + imageData;
}

// A button will call this function
//
function capturePhoto() {
  alert("function is called"); 
  if(_.isUndefined(navigator.camera)){
    alert("Camera is not defined");
  }else{
    alert("WTF?!");
  }
  // Take picture using device camera and retrieve image as base64-encoded string
  navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
    destinationType: destinationType.DATA_URL });
}

// Called if something bad happens.
//
function onFail(message) {
  alert('Failed because: ' + message);
}

</script>

<button onclick="capturePhoto();">Capture Photo</button> <br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />

I installed the camera plugin according to the CLI directions

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git

I also added the cordova.js files.

<script type="text/javascript" charset="utf-8" src="js/cordova-js/lib/cordova.js"></script>

回答1:


Where are you testing your code?

I dont know if you still need the anwser. But I think it can help someone. I run your code and it works 100%. I have tested in Android's emulator with a emulated Camera. I think that you forgot the uses permissions.

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

I made an example here https://github.com/paulorbpacheco/CameraTest-Cordova.git

I hope this can help you...

Regards




回答2:


This is a bit old, but I wanted to provide hopefully for insight to anyone else that might come along later...

The issue I was running into was caused by the fact I had done an older npm install of cordova at one point that was still on my system, and then later the npm install of phonegap.

Cordova is a dependency of phonegap so the necessary version of cordova was present, but when I would run the plugin install:

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git

the system was defaulting to the old version of cordova and as a result was not getting the correct version of the plugins.

I was reminded of this issue again recently when I upgraded my npm phonegap package from 3.0.0 to 3.1.0. Once again, the plugins changed and were not backwards compatible. In the case of 3.0.0, PhoneGap expects a plugin directory of

org.apache.cordova.core.camera org.apache.cordova.core.X

In the latest release 3.1.0 the core namespacing was dropped and these now look like this

org.apache.cordova.camera org.apache.cordova.X

In normal use scenarios I don't think this is something people run into on a daily basis. Most projects I'm guessing are being generated and the developer is adding the plugins they need and sticking to a particular release of PhoneGap until at some point maybe they decide to upgrade the project. Where this becomes an issue as I see it is when the developer starts working on multiple PhoneGap projects at the same time; the case I'm having here. I upgraded to a newer version for a new project, then needed to add plugins to the old project EXPLOSION OCCURS

Up to this point I had been using a global install of PhoneGap (per the official documentation at phonegap.com)

sudo npm install -g phonegap

My short term solution ended up being to cp the needed plugin directory from an old project that was using the version I needed over into my other project that happens to be running on the same version. My next steps will be to test out using nvm and see if I'm am able to use multiple installs of PhoneGap this way per project, rather than having an always shifting global version.




回答3:


Undefined issue generated because cordova is not properly builded, so Please follow the steps below in order to resolve navigator.camera issue

Step 1 : Grab latest phonegap zip (http://phonegap.com/install/) , right now latest build is 2.9.1 that contains cordova.2.9.1.js , but doesn't have cordova2.9.1.jar (You need to generate jar file, plz follow step 2)

step 2: Then you need to generate cordova2.9.1.jar , Follow this link below how to generate .jar file Where is cordova-2.7.0.jar?

Remember you have to have proper cordova.2.9.1.js and its respective cordova.2.9.1.jar in your android project in "Eclipse IDE"

Step 3: Don't forget to add camera permission in your config.xml (Please follow config.xml, if not works)

<------- Config.xml ------->

<?xml version="1.0" encoding="UTF-8"?>

<widget xmlns = "http://www.w3.org/ns/widgets"
        xmlns:gap = "http://phonegap.com/ns/1.0"
        id        = "myapp"
        version   = "1.0.0">

    <name>Sky Lite </name>

    <description>
        I am Rocking guy.
    </description>

    <author href="http://google.com" email="procks@gmail.com">
          This man rock your day.
    </author>

    <!--
        If you do not want any permissions to be added to your app, add the
        following tag to your config.xml; you will still have the INTERNET
        permission on your app, which PhoneGap requires.
    -->
    <preference name="permissions"                value="none"/>

    <!-- Customize your app and platform with the preference element. -->
    <preference name="phonegap-version"           value="3.6.0" />          <!-- all: current version of PhoneGap -->
    <preference name="orientation"                value="default" />        <!-- all: default means both landscape and portrait are enabled -->
    <preference name="target-device"              value="universal" />      <!-- all: possible values handset, tablet, or universal -->
    <preference name="fullscreen"                 value="true" />           <!-- all: hides the status bar at the top of the screen -->
    <preference name="prerendered-icon"           value="true" />           <!-- ios: if icon is prerendered, iOS will not apply it's gloss to the app's icon on the user's home screen -->
    <preference name="ios-statusbarstyle"         value="black-opaque" />   <!-- ios: black-translucent will appear black because the PhoneGap webview doesn't go beneath the status bar -->
    <preference name="detect-data-types"          value="true" />           <!-- ios: controls whether data types (such as phone no. and dates) are automatically turned into links by the system -->
    <preference name="exit-on-suspend"            value="false" />          <!-- ios: if set to true, app will terminate when home button is pressed -->
    <preference name="auto-hide-splash-screen"    value="true" />           <!-- ios: if set to false, the splash screen must be hidden using a JavaScript API -->
    <preference name="disable-cursor"             value="false" />          <!-- blackberry: prevents a mouse-icon/cursor from being displayed on the app -->
    <preference name="android-minSdkVersion"      value="7" />              <!-- android: MIN SDK version supported on the target device. MAX version is blank by default. -->
    <preference name="splashscreen" value="splash" />
    <preference name="splashScreenDelay" value="10000" />
    <preference name="android-installLocation"    value="auto" />           <!-- android: app install location. 'auto' will choose. 'internalOnly' is device memory. 
    'preferExternal' is SDCard. -->

    <!-- Plugins -->

    <!-- Core plugins -->
    <gap:plugin name="org.apache.cordova.battery-status" />
    <gap:plugin name="org.apache.cordova.camera" />
    <gap:plugin name="org.apache.cordova.CameraLauncher" />
    <gap:plugin name="org.apache.cordova.media" />
    <gap:plugin name="org.apache.cordova.media-capture" />
    <gap:plugin name="org.apache.cordova.console" />
    <gap:plugin name="org.apache.cordova.contacts" />
    <gap:plugin name="org.apache.cordova.device" />
    <gap:plugin name="org.apache.cordova.device-motion" />
    <gap:plugin name="org.apache.cordova.device-orientation" />
    <gap:plugin name="org.apache.cordova.dialogs" />
    <gap:plugin name="org.apache.cordova.file" />
    <gap:plugin name="org.apache.cordova.file-transfer" />
    <gap:plugin name="org.apache.cordova.geolocation" />
    <gap:plugin name="org.apache.cordova.globalization" />
    <gap:plugin name="org.apache.cordova.inappbrowser" />
    <gap:plugin name="org.apache.cordova.media" />
    <gap:plugin name="org.apache.cordova.network-information" />
    <gap:plugin name="org.apache.cordova.splashscreen" />
    <gap:plugin name="org.apache.cordova.vibration" />
    <gap:plugin name="com.phonegap.plugins.barcodescanner" />
    <gap:plugin name="com.phonegap.plugins.pushplugin" /> 
		
    <!-- Third party plugins -->
    <!-- A list of available plugins are available at https://build.phonegap.com/plugins -->
    <!-- 
        <gap:plugin name="com.phonegap.plugins.barcodescanner" />
    -->

    <!-- Define app icon for each platform. -->
    <icon src="../../assets/www/icon.png" />
    <icon src="../../assets/www/res/icon/android/icon-36-ldpi.png"   gap:platform="android"    gap:density="ldpi" />
    <icon src="../../assets/www/res/icon/android/icon-48-mdpi.png"   gap:platform="android"    gap:density="mdpi" />
    <icon src="../../assets/www/res/icon/android/icon-72-hdpi.png"   gap:platform="android"    gap:density="hdpi" />
    <icon src="../../assets/www/res/icon/android/icon-96-xhdpi.png"  gap:platform="android"    gap:density="xhdpi" />
    <icon src="../../assets/www/res/icon/blackberry/icon-80.png"     gap:platform="blackberry" />
    <icon src="../../assets/www/res/icon/blackberry/icon-80.png"     gap:platform="blackberry" gap:state="hover"/>
    <icon src="../../assets/www/res/icon/ios/icon-57.png"            gap:platform="ios"        width="57" height="57" />
    <icon src="../../assets/www/res/icon/ios/icon-72.png"            gap:platform="ios"        width="72" height="72" />
    <icon src="../../assets/www/res/icon/ios/icon-57-2x.png"         gap:platform="ios"        width="114" height="114" />
    <icon src="../../assets/www/res/icon/ios/icon-72-2x.png"         gap:platform="ios"        width="144" height="144" />
    <icon src="../../assets/www/res/icon/webos/icon-64.png"          gap:platform="webos" />
    <icon src="../../assets/www/res/icon/windows-phone/icon-48.png"  gap:platform="winphone" />
    <icon src="../../assets/www/res/icon/windows-phone/icon-173.png" gap:platform="winphone"   gap:role="background" />

    <!-- Define app splash screen for each platform. -->
    <gap:splash src="../../assets/www/res/screen/android/screen-ldpi-portrait.png"  gap:platform="android" gap:density="ldpi" />
    <gap:splash src="../../assets/www/res/screen/android/screen-mdpi-portrait.png"  gap:platform="android" gap:density="mdpi" />
    <gap:splash src="../../assets/www/res/screen/android/screen-hdpi-portrait.png"  gap:platform="android" gap:density="hdpi" />
    <gap:splash src="../../assets/www/res/screen/android/screen-xhdpi-portrait.png" gap:platform="android" gap:density="xhdpi" />
    <gap:splash src="../../assets/www/res/screen/blackberry/screen-225.png"         gap:platform="blackberry" />
    <gap:splash src="../../assets/www/res/screen/ios/screen-iphone-portrait.png"    gap:platform="ios"     width="320" height="480" />
    <gap:splash src="../../assets/www/res/screen/ios/screen-iphone-portrait-2x.png" gap:platform="ios"     width="640" height="960" />
    <gap:splash src="../../assets/www/res/screen/ios/screen-ipad-portrait.png"      gap:platform="ios"     width="768" height="1024" />
    <gap:splash src="../../assets/www/res/screen/ios/screen-ipad-landscape.png"     gap:platform="ios"     width="1024" height="768" />
    <gap:splash src="../../assets/www/res/screen/windows-phone/screen-portrait.jpg" gap:platform="winphone" />

    <!--
        Define access to external domains.

        <access />            - a blank access tag denies access to all external resources.
        <access origin="*" /> - a wildcard access tag allows access to all external resource.

        Otherwise, you can specify specific domains:
    -->
  <access origin=".*" />  
  <access origin="http://phonegap.com" /> 
  <access origin="https://mts.googleapis.com" subdomains="true"/>
    <access origin="https://mts0.googleapis.com" subdomains="true"/>
    <access origin="https://mts1.googleapis.com" subdomains="true"/>
    <access origin="https://maps.googleapis.com" subdomains="true"/>
    <access origin="https://fonts.googleapis.com" subdomains="true"/>
    <access origin="https://maps.gstatic.com" subdomains="true"/>
    <access origin="https://csi.gstatic.com" subdomains="true"/>
    <access origin="https://themes.googleusercontent.com" subdomains="true"/>
  

    <feature name="App">
      <param name="android-package" value="org.apache.cordova.App"/>
    </feature>
    <feature name="Geolocation">
      <param name="android-package" value="org.apache.cordova.GeoBroker"/>
    </feature>
    <feature name="Device">
      <param name="android-package" value="org.apache.cordova.Device"/>
    </feature>
    <feature name="Accelerometer">
      <param name="android-package" value="org.apache.cordova.AccelListener"/>
    </feature>
    <feature name="Compass">
      <param name="android-package" value="org.apache.cordova.CompassListener"/>
    </feature>
    <feature name="Media">
      <param name="android-package" value="org.apache.cordova.AudioHandler"/>
    </feature>
    <feature name="Camera">
      <param name="android-package" value="org.apache.cordova.CameraLauncher"/>
    </feature>
    <feature name="Contacts">
      <param name="android-package" value="org.apache.cordova.ContactManager"/>
    </feature>
    <feature name="File">
      <param name="android-package" value="org.apache.cordova.FileUtils"/>
    </feature>
    <feature name="NetworkStatus">
      <param name="android-package" value="org.apache.cordova.NetworkManager"/>
    </feature>
    <feature name="Notification">
      <param name="android-package" value="org.apache.cordova.Notification"/>
    </feature>
    <feature name="Storage">
      <param name="android-package" value="org.apache.cordova.Storage"/>
    </feature>
    <feature name="FileTransfer">
      <param name="android-package" value="org.apache.cordova.FileTransfer"/>
    </feature>
    <feature name="Capture">
      <param name="android-package" value="org.apache.cordova.Capture"/>
    </feature>
    <feature name="Battery">
      <param name="android-package" value="org.apache.cordova.BatteryListener"/>
    </feature>
    <feature name="SplashScreen">
      <param name="android-package" value="org.apache.cordova.SplashScreen"/>
    </feature>
    <feature name="Echo">
      <param name="android-package" value="org.apache.cordova.Echo"/>
    </feature>
    <feature name="Globalization">
      <param name="android-package" value="org.apache.cordova.Globalization"/>
    </feature>
    <feature name="InAppBrowser">
      <param name="android-package" value="org.apache.cordova.InAppBrowser"/>
    </feature>
  
      
   <!-- allow local pages -->
    <!--
        <access origin="http://phonegap.com" />                    - allow any secure requests to http://phonegap.com/
        <access origin="http://phonegap.com" subdomains="true" />  - same as above, but including subdomains, such as http://build.phonegap.com/
    -->

</widget>

Step 4 : Add Permission in your AndroidManifest.xml file

<------- AndroidManifest.xml --------->

<uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
	<uses-permission android:name="android.permission.VIBRATE" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
	<uses-permission android:name="android.permission.READ_PHONE_STATE" />
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.RECEIVE_SMS" />
	<uses-permission android:name="android.permission.RECORD_AUDIO" />
	<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
	<uses-permission android:name="android.permission.READ_CONTACTS" />
	<uses-permission android:name="android.permission.WRITE_CONTACTS" />
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
	<uses-permission android:name="android.permission.GET_ACCOUNTS" />
	<uses-permission android:name="android.permission.BROADCAST_STICKY" />
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Step 5 : Add code in your own javascript file (Plz check my js Code )

<----- my custom JS file ----->

$("#btnImageCaptured").on("click", function(e){
	alert("image uploading");
        e.preventDefault();
	e.stopPropagation();
	navigator.camera.getPicture(onSuccessImageAttachment, onFailImageAttachment,
		{quality:50,
		destinationType: Camera.DestinationType.FILE_URI,
		sourceType : Camera.PictureSourceType.CAMERA,
		//encodingType: navigator.camera.EncodingType.PNG,
		allowEdit: true,
		targetWidth: 200, targetHeight: 200});
		//targetWidth: 100, targetHeight: 150,
		//mediaType : Camera.MediaType.PICTURE
		//sourceType:navigator.camera.PictureSourceType.PHOTOLIBRARY});
    });

function onSuccessImageAttachment(imageData){
    window.alert("success");
    //window.alert("Prishah took Image successfully : " + imageData);
    window.location.href = "#orderAttachedLotImage";
    $("#imgAttachedLot").attr('src','data:image/jpeg;base64,' + imageData);
    //$("#imgAttachedLot").src = "data:image/jpeg;base64," +  imageData;
    //TODO : Insert new Image request to the server
    //TODO : Display Image
}
function onFailImageAttachment(failMsg) {
    window.alert("Failed to image uploading :" + failMsg);
}

Step 6(Optional) : Try turning off multitasking to see if it helps. In your java app, add:

super.setBooleanProperty("keepRunning", false);

<------ My java Code --------->

@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setIntegerProperty("splashscreen", R.drawable.screen_hdpi_portrait);
		super.setBooleanProperty("keepRunning", false); //For Camera 
		super.loadUrl("file:///android_asset/www/index.html", 2000);
		 
		//pinch zooming Capabilities
		WebSettings ws = super.appView.getSettings();
	    ws.setSupportZoom(true);
	    ws.setBuiltInZoomControls(true);
	    
		}



回答4:


Use this to supress the camera in the desktop mode

function onDeviceReady() {
  try {
      pictureSource = navigator.camera.PictureSourceType;
      destinationType = navigator.camera.DestinationType;
  } catch (e) {

  }
}



回答5:


Hi You could try using Icenium http://www.icenium.com/ and there create a Phonegap project where there will be already sample application with camera API is done and you could find the code there.

Hope this helps



来源:https://stackoverflow.com/questions/18690388/phonegap-cordova-3-0-0-navigator-camera-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!