Not able to turn off webcam - javascript

I've written a script that successfully activates the user's webcam but throws an error when I try to stop or pause the stream.
I've built a prototype for multi-part single page webapp that requires the user to activate then deactivate their webcam. this version of the prototype doesn't actually capture and store webcam images and it's especially important that the user is able to deactivate the camera so that they don't feel like they're under surveillance.
Below are is my script, which uses a webRTC feature detection lib called compatibility. the line $video.pause() causes the following error
"Uncaught TypeError: undefined is not a function" in Chrome 36.x
while typing "$video" in devtools nad hitting return gives me this
[​​] but doing $video[0].pause() gives me the same error message as above.
I was thinking that doing something like window.URL.revokeObjectURL(stream) -- in my case compatibility.URL.revokeObjectURL(stream) -- was the way to go but wanted to get some advise before diving into that
// get it
var smoother = new Smoother(0.85, [0, 0, 0, 0, 0]),
$video = $("#v"),
$local_media = null;
webcam_capture = function(x){
try {
compatibility.getUserMedia({video: true}, function(stream) {
try {
$video.attr('src', compatibility.URL.createObjectURL(stream));
} catch (error) {
$video.attr(src, stream);
}
$('.camera_prompt').removeClass('show')
}, function (error) {
alert("WebRTC not available");
});
} catch (error) {
console.log(error);
}
}
webcam_capture();
// warn - prompt permissions after 6 seconds
capture_error = setTimeout(function(){
typeof $video.attr('src') == "undefined" ?
$('.camera_prompt').addClass('show') :
clearTimeout(capture_error);
},3000)
start_card_capture = function(x){
// open capture sesh
OAO.card_capture_status = true;
// get id of input to focus and class
var id = 'capture_' + x;
$('input#' + id).addClass('focused');
// UI fade in
$('#v, .notification, button.capture').fadeIn();
}
end_card_capture = function(x){
// close capture sesh
OAO.card_capture_status = false;
// UI fade out
$('#v, .notification, button.capture').fadeOut('visible');
}
capture_notify = function(x){
$('#card_capture_form').find('.notification').find('div').text(x)
}
$('.capture').on('click', function(e){
// determine input
var $f = $(this).parent('form')
$i = $f.find('input.focused');
// check input and update the associated label's icon
$i.prop('checked', true).removeClass('focused');
$i.next('label').addClass('captured');
// close UI
if($f.find('label.captured').length < 2){
end_card_capture(e)
}
if($f.find('label.captured').length == 2){
$video.pause();
OAO.sectional_transition('#funding',{y: '0%'}, 1400,100, $(this).parents('section'), { y: '-250%' }, 1000, 100 );
OAO.step = 2;
OAO.progress_bar(OAO.step)
$('#progress_bar_container').removeClass('hidden');
}
});
$('.capture_front, .capture_back').on('click', function(){
// determine which side
$(this).hasClass('capture_front') ?
OAO.card_capture_side = 'front' :
$(this).hasClass('capture_back') ?
OAO.card_capture_side = 'back' :
C('whichsideofthecardamIshooting?');
if(typeof $video.attr('src') !== "undefined"){
// set prop and init capture
capture_notify(OAO.card_capture_side);
start_card_capture(OAO.card_capture_side)
}
});
Thanks in advance for your help

Related

javascript alert box close automatically

I need a function, which close the alert box (window) in few seconds automatically:
$("#upload-btn").on('click', function() {
var dt = canvas.toDataURL('image/jpeg');
if (window.Lollipop) {
window.Lollipop.save(dt);
}
$.post('saveImage.php',
{
img : dt
}, function(data) {
if(data){
alert("Image Saved");
}
});
There is no web api function to close the opened alert.
It's NOT possible via standard Web API to close the standard alert box, but you can define your own function or override the alert() function (which is the bad way, better to define own).
const temporaryAlert = function( text, duration ) {
console.assert(typeof text === "string");
console.assert(text.length > 0);
console.assert(typeof duration === "number");
const item = document.createElement("div");
item.innerText = text;
// item.style - add some CSS-stuff to customize the box style
window.setTimeout(() => item.parentNode.removeChild(item), duration);
return document.body.appendChild(item);
};

Determine when a boolean changes from true to false

I've got a webpage that has a print button. As soon as the print button is pressed I have a function
function pWindowNeeded() {
if (newPWindowNeeded == 'Y') {
return true;
}
return false;
}
then I have another function that says if it is true then open a new window containing a PDF to be printed and change the newPWindowNeeded to 'N'
this all works fine.
Also when the user clicks the print window right now I have this function being run
function alertWindow()
{
var w = window.open('','',' width = 200, height = 200, top = 250 , left = 500 ');
w.document.write("Please Wait<br> Creating Document(s).<br><img src='loadingimage.gif'>");
w.focus();
setTimeout(function() {w.close();}, 5000);
}
This also works fine, the window is created and then after 5 seconds it automatically closes.
This works fine for now but what I actually need is to evaluate when pWindowNeeded returns false and when it does return false I need it to automatically close the window.
What is the most effective way to evaluate when pWindowNeeded has changed from true to false?
Thanks
The least efficient and easiest way to do it is to poll for the value using setTimeout.
function callbackWhenWindowNotNeeded(cb) {
if (!pWindowNeeded()) {
cb();
} else {
// The lower the number, the faster the feedback, but the more
// you hog the system
setTimeout(callbackWhenWindowNotNeeded, 100);
}
}
function alertWindow() {
var w = window.open('','',' width = 200, height = 200, top = 250 , left = 500 ');
w.document.write("Please Wait<br> Creating Document(s).<br><img src='loadingimage.gif'>");
w.focus();
callBackWhenWindowNotNeeded(function() {
w.close();
});
}
Ideally you'd use some sort of MessageBus to prevent polling. Here's an example with a poor man's bus.
var MessageBus = (function(){
var listeners = [];
return {
subscribe: function(cb) {
listeners.push(cb);
},
fire: function(message) {
listeners.forEach(function(listener){
listener.call(window);
});
}
})();
function alertWindow() {
var w = window.open('','',' width = 200, height = 200, top = 250 , left = 500 ');
w.document.write("Please Wait<br> Creating Document(s).<br><img src='loadingimage.gif'>");
w.focus();
MessageBus.subscribe(function(message, event) {
if (message == 'WINDOW_NOT_NEEDED') {
w.close();
}
});
}
// Then wherever you set your newPWindowNeeded
newPWindowNeeded = 'N';
MessageBus.fire('WINDOW_NOT_NEEDED');

How to link js pages in Titanium?

I'm a beginner coder whose trying to link my js pages together such that when I click on a button it will open up the window of the other js file. However I keep getting the following error message:
"Message: Uncaught TypeError: object is not a function
[ERROR] : TiExceptionHandler: (main) [0,654] - Source: new Window().open();"
whenever I run my application.
Code for my app.js file:
var NavigationController = require('NavigationController').NavigationController,
ApplicationWindow = require('ui/handheld/android/ApplicationWindow').ApplicationWindow;
//create NavigationController which will drive our simple application
var controller = new NavigationController();
//open initial window
controller.open(new ApplicationWindow(this.controller));
Code for my main/home window: (in ApplicationWindow.js)
//Application Window Component Constructor
exports.ApplicationWindow = function(navController) {
//----------------Main Page-------------------------
var winMainPage = Titanium.UI.createWindow({
title:'Radio',
backgroundColor: 'transparent',
});
.
.
.
//open second window
var CategoryButton = Titanium.UI.createButton({
bottom: 20,
left: 50,
width: 60,
height: 60,
backgroundImage: '/images/category.png',
backgroundSelectedImage:'/images/category.gif',
backgroundDisabledImage: '/images/categoryoff.gif',
backgroundColor: 'transparent'
});
//Action listener
CategoryButton.addEventListener('click', function() {
navController.open(new PlayMusic(navController));
});
//to exit app by clicking return button
winMainPage.addEventListener('androidback', function(e){
var confirmClear = Titanium.UI.createAlertDialog({
message:'Exit App?',
buttonNames: ['Yes','No']
});
confirmClear.show();
confirmClear.addEventListener('click',function(e) {
if (e.index === 0) {
winMainPage.close();
}
});
winMainPage.open();
});
return winMainPage;
}
Code in second window: (in PlayMusic.js)
exports.PlayMusic = function(navController){
var self = Ti.UI.createWindow({
backgroundColor:'#ffffff',
navBarHidden:true,
exitOnClose:true
});
.
.
.
return self;
}
The Navigation controller window: (NavigationController.js)
exports.NavigationController = function() {
this.windowStack = [];
};
exports.NavigationController.prototype.open = function(/*Ti.UI.Window*/windowToOpen) {
//add the window to the stack of windows managed by the controller
this.windowStack.push(windowToOpen);
//grab a copy of the current nav controller for use in the callback
var that = this;
windowToOpen.addEventListener('close', function() {
that.windowStack.pop();
});
//hack - setting this property ensures the window is "heavyweight" (associated with an Android activity)
windowToOpen.navBarHidden = windowToOpen.navBarHidden || false;
//This is the first window
if(this.windowStack.length === 1) {
if(Ti.Platform.osname === 'android') {
windowToOpen.exitOnClose = true;
windowToOpen.open();
} else {
this.navGroup = Ti.UI.iPhone.createNavigationGroup({
window : windowToOpen
});
var containerWindow = Ti.UI.createWindow();
containerWindow.add(this.navGroup);
containerWindow.open();
}
}
//All subsequent windows
else {
if(Ti.Platform.osname === 'android') {
windowToOpen.open();
} else {
this.navGroup.open(windowToOpen);
}
}
};
//go back to the initial window of the NavigationController
exports.NavigationController.prototype.home = function() {
//store a copy of all the current windows on the stack
var windows = this.windowStack.concat([]);
for(var i = 1, l = windows.length; i < l; i++) {
(this.navGroup) ? this.navGroup.close(windows[i]) : windows[i].close();
}
this.windowStack = [this.windowStack[0]]; //reset stack
};
Sorry if the way I present my question is unclear. Can anyone please tell me where I've gone wrong? Thanks in advance :)
Pay close attention to your error message:
Message: Uncaught TypeError: object is not a function [ERROR] : TiExceptionHandler: (main) [0,654] - Source: new Window().open();
It looks like you you might be defining Window as an object somewhere and not as a function. Your shared code does not currently show the declaration of Window, however, based on your error message I would say that checking its type is a good place to start debugging. If you could post the declaration of Window it would be much easier to help you :)

Console.log Internet explorer 8 particular case [duplicate]

This question already has answers here:
'console' is undefined error for Internet Explorer
(21 answers)
Closed 8 years ago.
Hi i found the problem in other stackoverflow questions , the problem is i have tried all solutions that should work, but i think im not understanding where and how to implement that fixes..
My problem is console.log in internet explorer throws an error as undefined. I search and found
Console undefined issue in IE8
Internet Explorer: "console is not defined" Error
I try to wrap the code inside the function using a condition like 'if(window.console) '
this dosent work i even try most of the recommended contitions no one work, try to insert the snnipet in the code so it worked, but it dont..
Im obviously not understanding how and where to put does fixes. Sorry for my ignorance. but im in a hurry, need to someone points at my stupidity
Thanks
var jcount = 0;
var scroll_count = 0;
var playflag=1;
var ajxcallimiter=0;
var hp_totalcount=parseInt($("#hp_totalcount").val());
if(hp_totalcount<5)
hp_totalcount=5;
function hlist_slider()
{
if($(".items img").eq(jcount).length != 0 && playflag==1){
firedstyle();
console.log(jcount);
$(".items img").eq(jcount).trigger("mouseover");
if(jcount % 5 === 0 && jcount!=0)
{
console.log('scroll');
api.next();
scroll_count++;
}
jcount++; // add to the counter
if(jcount>hp_totalcount)
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}scroll_count=1;
}
}
}
else if(jcount<hp_totalcount && playflag==1)
{
playflag=0;homepagelist_nextclick();playflag=1;
}
else
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}
scroll_count=1;
}
}
}
$(function() {
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
hlist_slider();
setInterval(hlist_slider,10000);
// provide scrollable API for the action buttons
window.api = root.data("scrollable");
});
function firedstyle()
{
$(".items img").on("hover",function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("t_", "");
var tbtit = $(this).siblings('.tbtit').text();
var tbdesc = $(this).siblings('.tbdescp').text();
var tbtitgoto = $(this).attr("data");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").stop(true, true).fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap.find(".img-info h4").text(tbtit);
wrap.find(".img-info p").text( tbdesc);
wrap.find("a").attr("href", tbtitgoto);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").trigger("mouseover");
}
function toggle(el){
if(el.className!="play")
{
playflag=0;
el.className="play";
el.src='images/play.png';
//api.pause();
}
else if(el.className=="play")
{
playflag=1;
el.className="pause";
el.src='images/pause.png';
// api.play();
}
return false;
}
function hp_nxtclick()
{
homepagelist_nextclick();
console.log('scroll');
if(api.next()){
scroll_count++;}
}
function homepagelist_nextclick()
{
var hp_totalcount=parseInt($("#hp_totalcount").val());
var hp_count=parseInt($("#hp_count").val());
if(hp_totalcount==0 || hp_count >=hp_totalcount)
return ;
if(ajxcallimiter==1)
return;
else
ajxcallimiter=1;
$.ajax(
{
type: "GET",
url: "<?php echo $makeurl."index/homepageslide/";?>"+hp_count,
success: function(msg)
{
hp_count=parseInt($("#hp_count").val())+parseInt(5);
$("#hp_count").val(hp_count);
$("#hp_list").append(msg);ajxcallimiter=0;
}
});
}
The problem is that the console (developer tool panel) needs to be active on page-load*.
Hit F12, reload your page, and you should get what you're looking for.
*Just to clarify: The developer panel needs to be open prior to window.console being called/tested. I'm assuming your code is being run on-load.
This should work:
if(!window.console || !window.console.log) window.console = {log: function(){}};
This way you will be able to use console.log without producing errors.
In my code, I put this snippet at the top - before any other javascript that might try to use the console loads:
if (window.console == null) {
window.console = {
log: function() {},
warn: function() {},
info: function() {},
error: function() {}
};
}
Or in coffeescript:
if not window.console?
window.console = {
log: () ->
warn: () ->
info: () ->
error: () ->
}
This provides a dummy console for browsers that don't include one.

bug in closing tooltip on esc

I am just a beginner in jquery. I have used the tooltip script from this site. http://www.twinhelix.com/dhtml/supernote/demo/#demo4 .They used the following function to close the tooltip on clicking the close button.
<script type="text/javascript">
// SuperNote setup: Declare a new SuperNote object and pass the name used to
// identify notes in the document, and a config variable hash if you want to
// override any default settings.
var supernote = new SuperNote('supernote', {});
// Available config options are:
//allowNesting: true/false // Whether to allow triggers within triggers.
//cssProp: 'visibility' // CSS property used to show/hide notes and values.
//cssVis: 'inherit'
//cssHid: 'hidden'
//IESelectBoxFix: true/false // Enables the IFRAME select-box-covering fix.
//showDelay: 0 // Millisecond delays.
//hideDelay: 500
//animInSpeed: 0.1 // Animation speeds, from 0.0 to 1.0; 1.0 disables.
//animOutSpeed: 0.1
// You can pass several to your "new SuperNote()" command like so:
//{ name: value, name2: value2, name3: value3 }
// All the script from this point on is optional!
// Optional animation setup: passed element and 0.0-1.0 animation progress.
// You can have as many custom animations in a note object as you want.
function animFade(ref, counter)
{
//counter = Math.min(counter, 0.9); // Uncomment to make notes translucent.
var f = ref.filters, done = (counter == 1);
if (f)
{
if (!done && ref.style.filter.indexOf("alpha") == -1)
ref.style.filter += ' alpha(opacity=' + (counter * 100) + ')';
else if (f.length && f.alpha) with (f.alpha)
{
if (done) enabled = false;
else { opacity = (counter * 100); enabled=true }
}
}
else ref.style.opacity = ref.style.MozOpacity = counter*0.999;
};
supernote.animations[supernote.animations.length] = animFade;
// Optional custom note "close" button handler extension used in this example.
// This picks up click on CLASS="note-close" elements within CLASS="snb-pinned"
// notes, and closes the note when they are clicked.
// It can be deleted if you're not using it.
addEvent(document, 'click', function(evt)
{
var elm = evt.target || evt.srcElement, closeBtn, note;
while (elm)
{
if ((/note-close/).test(elm.className)) closeBtn = elm;
if ((/snb-pinned/).test(elm.className)) { note = elm; break }
elm = elm.parentNode;
}
if (closeBtn && note)
{
var noteData = note.id.match(/([a-z_\-0-9]+)-note-([a-z_\-0-9]+)/i);
for (var i = 0; i < SuperNote.instances.length; i++)
if (SuperNote.instances[i].myName == noteData[1])
{
setTimeout('SuperNote.instances[' + i + '].setVis("' + noteData[2] +
'", false, true)', 100);
cancelEvent(evt);
}
}
});
// Extending the script: you can capture mouse events on note show and hide.
// To get a reference to a note, use 'this.notes[noteID]' within a function.
// It has properties like 'ref' (the note element), 'trigRef' (its trigger),
// 'click' (whether its shows on click or not), 'visible' and 'animating'.
addEvent(supernote, 'show', function(noteID)
{
// Do cool stuff here!
});
addEvent(supernote, 'hide', function(noteID)
{
// Do cool stuff here!
});
// If you want draggable notes, feel free to download the "DragResize" script
// from my website http://www.twinhelix.com -- it's a nice addition :).
</script>
I have tried to edit this function for closing the tooltip on clicking the esckey too. But i couldn't. How can i modify the function?

Categories