简体   繁体   中英

Uncaught TypeError: Cannot read property 'getBarCode' of undefined (JavaScript)

Im trying to implement a webcam decoder into my MVC4 project, i have everything near enough working except for one issue. During debugging i notice that when i click on the decode button i get an error in the google chromes debugger for javascript, stating the following "Uncaught TypeError: Cannot read property 'getBarCode' of undefined ". I presume it has something to do with the format of onclick method (See below) however after numerous tries at formatting it i still get the same error. I have included the Js file and my cshtml view as well

QR.cshtml

@{
    ViewBag.Title = "Webcam";
}

        <script>
            //$(document).ready(function () {
                $("#webcam").scriptcam({
                    path:'~/Scripts/',
                    readBarCodes: 'QR_CODE',
                    onError: onError,
                    cornerRadius: 0,
                    onWebcamReady: onWebcamReady
                });
            //});

            function onError(errorId, errorMsg) {
                alert(errorMsg);
            }
            function changeCamera() {
                $.scriptcam.changeCamera($('#cameraNames').val());
            }
            function onWebcamReady(cameraNames, camera, microphoneNames, microphone, volume) {
                $.each(cameraNames, function (index, text) {
                    $('#cameraNames').append($('<option></option>').val(index).html(text))
                });
                $('#cameraNames').val(camera);
            }
        </script> 


        <div style="width:330px;float:left;">
            <object type="application/x-shockwave-flash" data="~/Scripts/scriptcam.swf" width="320" height="240" id="webcam" style="visibility: visible;"><param name="menu" value="false"><param name="wmode" value="direct"><param name="allowScriptAccess" value="always"><param name="allowFullScreen" value="true"><param name="flashvars" value="width=320&amp;height=240&amp;chatWindow=chatWindow&amp;path=&amp;zoom=1&amp;zoomChat=1&amp;rotate=0&amp;skewX=0&amp;skewY=0&amp;flip=0&amp;noFlashFound=%3Cp%3EYou%20need%20%3Ca%20href%3D%22http%3A%2F%2Fwww.adobe.com%2Fgo%2Fgetflashplayer%22%3EAdobe%20Flash%20Player%2011.7%3C%2Fa%3E%20to%20use%20this%20software.%3Cbr%2F%3EPlease%20click%20on%20the%20link%20to%20download%20the%20installer.%3C%2Fp%3E&amp;onError=function%20onError(errorId%2CerrorMsg)%20%7B%0A%09%09%09%09alert(errorMsg)%3B%0A%09%09%09%7D&amp;cornerRadius=0&amp;onWebcamReady=function%20onWebcamReady(cameraNames%2Ccamera%2CmicrophoneNames%2Cmicrophone%2Cvolume)%20%7B%0A%09%09%09%09%24.each(cameraNames%2C%20function(index%2C%20text)%20%7B%0A%09%09%09%09%09%24('%23cameraNames').append(%20%24('%3Coption%3E%3C%2Foption%3E').val(index).html(text)%20)%0A%09%09%09%09%7D)%3B%20%0A%09%09%09%09%24('%23cameraNames').val(camera)%3B%0A%09%09%09%7D&amp;id=webcam"></object>
            <div style="margin:5px;">
                <img src="webcamlogo.png" style="vertical-align:text-top">
                <select id="cameraNames" size="1" onchange="changeCamera()" style="width:245px;font-size:10px;height:25px;">
                <option value="0">In Built Camera</option></select>
            </div>
        </div>
        <div style="width:135px;float:left;">
            <p><button class="btn btn-small" id="btn1" onclick="$('#decoded').text($.scriptcam.getBarCode());">Decode image</button></p>
        </div>
        <div style="width:200px;float:left;">
            <p id="decoded"></p>
        </div>

Scriptcam.js

(function($) {
    $.fn.scriptcam=function(options) {
        // merge passed options with default values
        var opts=$.extend({}, $.fn.scriptcam.defaults, options);
        // off we go
        return this.each(function() {
            // add flash to div
            opts.id=this.id; // add id of plugin to the options structure
            data=opts; // pass options to jquery internal data field to make them available to the outside world
            data.path=decodeURIComponent(data.path); // convert URI back to normal string
            $('#'+opts.id).html(opts.noFlashFound); // inject no flash found message
            // forward incoming flash movie calls to outgoing functions
            $.scriptcam.SC_promptWillShow=data.promptWillShow;
            $.scriptcam.SC_fileReady=data.fileReady;
            $.scriptcam.SC_fileConversionStarted=data.fileConversionStarted;
            $.scriptcam.SC_onMotion=data.onMotion;
            $.scriptcam.SC_onError=data.onError;
            $.scriptcam.SC_onHandLeft=data.onHandLeft;
            $.scriptcam.SC_onHandRight=data.onHandRight;
            $.scriptcam.SC_onWebcamReady=data.onWebcamReady;
            $.scriptcam.SC_connected=data.connected;
            $.scriptcam.SC_onPictureAsBase64=data.onPictureAsBase64;
            $.scriptcam.SC_disconnected=data.disconnected;
            $.scriptcam.SC_setVolume=data.setVolume;
            $.scriptcam.SC_timeLeft=data.timeLeft;
            $.scriptcam.SC_userLeft=data.userLeft;
            $.scriptcam.SC_userJoined=data.userJoined;
            $.scriptcam.SC_addChatText=function(value) {
                value = value.replace(":{", '<img src="'+data.path+'angry.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":-{", '<img src="'+data.path+'angry.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":)", '<img src="'+data.path+'smile.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":-)", '<img src="'+data.path+'smile.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":D", '<img src="'+data.path+'biggrin.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":-D", '<img src="'+data.path+'biggrin.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":O", '<img src="'+data.path+'ohmy.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":-O", '<img src="'+data.path+'ohmy.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":(", '<img src="'+data.path+'sad.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":-(", '<img src="'+data.path+'sad.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":p", '<img src="'+data.path+'tongue.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(":-p", '<img src="'+data.path+'tongue.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(";)", '<img src="'+data.path+'wink.gif" width="16" height="16" class="smiley"/>');
                value = value.replace(";-)", '<img src="'+data.path+'wink.gif" width="16" height="16" class="smiley"/>');
                $('#'+data.chatWindow).append(value+'<br/>');
                $('#'+data.chatWindow).animate({ scrollTop: $('#'+data.chatWindow).prop("scrollHeight") - $('#'+data.chatWindow).height() }, 100);
            }
            if (opts.canvasHeight && opts.canvasHeight) {
                var newWidth=opts.canvasWidth;
                var newHeight=opts.canvasHeight;
            }
            else {
                // no canvas dimensions given, make our own horizontal layout
                var newWidth=opts.width*opts.zoom;
                var newHeight=opts.height*opts.zoom;
                if (opts.chatRoom) {
                    newWidth=(opts.width*opts.zoom)+(opts.width*opts.zoomChat)+5; // make room for two horizontal video windows with a margin of 5
                    opts.posX=(opts.width*opts.zoom)+5;
                    newHeight=opts.height*Math.max(opts.zoom,opts.zoomChat);
                };
            }
            // make new dimensions are not below minimum flash size
            if (newWidth < 215) {
                newWidth=215;
            }
            if (newHeight < 138) {
                newHeight=138;
            }
            if (opts.rotate!=0 || opts.skewX!=0 || opts.skewY!=0 || opts.flip!=0 || opts.zoom!=1 || opts.zoomChat!=1) {
                // no GPU acceleration
                var params = {
                    menu: 'false',
                    wmode: 'window',
                    allowScriptAccess: 'always',
                    allowFullScreen: 'true'
                };
            }
            else {
                // GPU acceleration when no filter is used
                var params = {
                    menu: 'false',
                    wmode: 'direct',
                    allowScriptAccess: 'always',
                    allowFullScreen: 'true'
                };
            };
            // Escape all values contained in the flashVars (IE needs this)
            for (var key in opts) {
                opts[key] = encodeURIComponent(opts[key]);
            };
            if (fileExists(decodeURIComponent(data.path)+'scriptcam.swf')) {
                swfobject.embedSWF(decodeURIComponent(data.path)+'scriptcam.swf', opts.id, newWidth, newHeight, '11.6', false, opts, params);
            }
            else {
                alert(decodeURIComponent(data.path)+'scriptcam.swf not found, please check the path parameter');
            }
        });
    };

    function fileExists(url) {
        var http = new XMLHttpRequest();
        http.open('HEAD', url, false);
        http.send();
        return http.status==200;
    }

    $.scriptcam={};

    // outgoing functions (calling the flash movie)

    $.scriptcam.getFrameAsBase64=function() {
        return $('#'+data.id).get(0).SC_getFrameAsBase64();
    }

    $.scriptcam.version=function() {
        return $('#'+data.id).get(0).SC_version();
    }

    $.scriptcam.hardwareacceleration=function() {
        return $('#'+data.id).get(0).SC_hardwareacceleration();
    }

    $.scriptcam.getMotionParameters=function() {
        $('#'+data.id).get(0).SC_getMotionParameters();
    }

    $.scriptcam.getBarCode=function() {
        return $('#'+data.id).get(0).SC_getBarCode();
    }

    $.scriptcam.startRecording=function() {
        $('#'+data.id).get(0).SC_startRecording();
    }

    $.scriptcam.pauseRecording=function() {
        $('#'+data.id).get(0).SC_pauseRecording();
    }

    $.scriptcam.resumeRecording=function() {
        $('#'+data.id).get(0).SC_resumeRecording();
    }

    $.scriptcam.closeCamera=function() {
        $('#'+data.id).get(0).SC_closeCamera();
    }

    $.scriptcam.changeVolume=function(value) {
        $('#'+data.id).get(0).SC_changeVolume(value);
    }

    $.scriptcam.sendMessage=function(value) {
        $('#'+data.id).get(0).SC_sendMessage(value);
    }

    $.scriptcam.playMP3=function(value) {
        $('#'+data.id).get(0).SC_playMP3(value);
    }

    $.scriptcam.changeCamera=function(value) {
        $('#'+data.id).get(0).SC_changeCamera(value);
    }

    $.scriptcam.changeMicrophone=function(value) {
        $('#'+data.id).get(0).SC_changeMicrophone(value);
    }

    // set javascript default values (flash default values are managed in the swf file)
    $.fn.scriptcam.defaults={
        width:320,
        height:240,
        chatWindow:'chatWindow',
        path:'',
        zoom:1,
        zoomChat:1,
        rotate:0,
        skewX:0,
        skewY:0,
        flip:0,
        noFlashFound:'<p>You need <a href="http://www.adobe.com/go/getflashplayer">Adobe Flash Player 11.7</a> to use this software.<br/>Please click on the link to download the installer.</p>'
    };
})(jQuery);

// incoming functions (calls coming from flash) - must be public and forward calls to the scriptcam plugin

function SC_onError(errorId,errorMsg) {
    $.scriptcam.SC_onError(errorId,errorMsg);
}

function SC_fileReady(fileName) {
    $.scriptcam.SC_fileReady(fileName);
}

function SC_fileConversionStarted(fileName) {
    $.scriptcam.SC_fileConversionStarted(fileName);
}

function SC_onMotion(decodedString) {
    $.scriptcam.SC_onMotion(decodedString);
}

function SC_promptWillShow() {
    $.scriptcam.SC_promptWillShow();
}
function SC_onHandLeft() {
    $.scriptcam.SC_onHandLeft();
}
function SC_onHandRight() {
    $.scriptcam.SC_onHandRight();
}
function SC_onWebcamReady(cameraNames,camera,microphoneNames,microphone) {
    $.scriptcam.SC_onWebcamReady(cameraNames,camera,microphoneNames,microphone);
}

function SC_onPictureAsBase64(value) {
    $.scriptcam.SC_onPictureAsBase64(value);
}

function SC_connected() {
    $.scriptcam.SC_connected();
}

function SC_disconnected() {
    $.scriptcam.SC_disconnected();
}

function SC_setVolume(value) {
    $.scriptcam.SC_setVolume(value);
}

function SC_onMotion(motion,brightness,color,motionx,motiony) {
    $.scriptcam.SC_onMotion(motion,brightness,color,motionx,motiony);
}

function SC_timeLeft(value) {
    $.scriptcam.SC_timeLeft(value);
}

function SC_addChatText(value) {
    $.scriptcam.SC_addChatText(value);
}

function SC_userJoined(value) {
    $.scriptcam.SC_userJoined(value);
}

function SC_userLeft(value) {
    $.scriptcam.SC_userLeft(value);
}

UPDATE

Basically what im trying to acheive https://www.scriptcam.com/demo_5.cfm

Upon further inspection i found that this works no problem on webforms but in MVC its a mess. Anyone have any luck implementing in MVC?

If you haven't modified the scriptcam library then my guess is that yes, the issues surrounds your onclick handler or the possibility that $ is not defined in the the current scope. I would advise against writing JS code in html markup as you cannot debug it (using chrome dev tools for example).

Instead, define the click handler in JS, ie:

$("#yourButtonId").click(function(){
    // Handle click...
});

The next thing i would advise is that you break up your function calls and use the JS debugger to figure out what is actually undefined. Is it the $?, try using JQuery.scriptcam... instead, or as Jason mentioned try calling it like a function. Finally, make sure the scripts have loaded correctly first before trying to call the given methods.

Chrome dev tools (F12) is your friend.

由于发生了更多问题,脚本摄像头被抛弃了,决定改用JSQRcode代码,谢谢您的帮助:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM