I am trying to implement open tok for my video chat application.
I am using opentok.min.js v 2.2.9 with php SDK. It is working fine with google chrome and firefox.
According to their announcements, it should work in IE with 32 bit OS.
https://tokbox.com/opentok/libraries/client/js/release-notes.html
But it is not working for me at any version of IE.
Anybody knows how to implement it for IE?
// Detect whether this browser is IE
var isNotIE = function isIE() {
var userAgent = window.navigator.userAgent.toLowerCase(),
appName = window.navigator.appName;
return !(appName === 'Microsoft Internet Explorer' || // IE <= 10
(appName === 'Netscape' && userAgent.indexOf('trident') > -1)); // IE >= 11
};
function connect() {
if (isNotIE() && OT.checkSystemRequirements()) {
session = OT.initSession(apiKey, sessionId);
sendMessage("Session has initialized. Connecting to session ... ");
session.on({
streamCreated: function(event) {
sendMessage("New stream in the session: " + event.stream.streamId);
var parentDiv = document.getElementById(subscriberElement);
var replacementDiv = document.createElement("div"); // Create a div for the publisher to replace
replacementDiv.id = "opentok_subscriber";
parentDiv.appendChild(replacementDiv);
subscriber = session.subscribe(event.stream, replacementDiv, subscriberProperties, function(error) {
if (error) {
console.log(error);
} else {
console.log("Subscriber added.");
}
});
},
streamDestroyed: function(event) {
sendMessage("Stream stopped streaming. Reason: " + event.reason)
},
signal: function(event) {
sendMessage("Signal sent from connection " + event.from.id);
// Process the event.data property, if there is any data.
}
});
session.connect(token, function(error) {
if (error) {
sendMessage("Error connecting: ", error.code, error.message);
} else {
sendMessage("Connected to the session successfully.");
displayBtn('connected');
}
});
}else{
sendMessage("What Should I do if it is IE?? :(");
}
}
function sendMessage(message) {
message = '<br>' + message;
$("#statusbox").append(message);
}
Now that IE versions 8-11 are supported by the plugin, you shouldn't need to switch on the isNotIE() && OT.checkSystemRequirements() condition, you can just use the same code path for all of those browsers.
It may still be a good idea to detect IE versions that are outside that range to let the user know that the feature of your application that uses OpenTok is not supported with some suggestions to upgrade/install.
Otherwise, one code suggestion: In the streamCreated event handler, rather than using 4 lines of code to create a new DOM element and then add it to a container, you can use the insertMode: "append" option. This works for both Publishers and Subscribers.
Before:
var parentDiv = document.getElementById(subscriberElement);
var replacementDiv = document.createElement("div"); // Create a div for the publisher to replace
replacementDiv.id = "opentok_subscriber";
parentDiv.appendChild(replacementDiv);
subscriber = session.subscribe(event.stream, replacementDiv, subscriberProperties, function(error) {
if (error) {
console.log(error);
} else {
console.log("Subscriber added.");
}
});
After:
subscriber = session.subscribe(event.stream, document.getElementById(subscriberElement), { insertMode: "append" }, function (error) {
if (error) {
console.log(error);
} else {
console.log("Subscriber added.");
// Set the ID of the DOM element if thats used elsewhere in the code
subscriber.element.id = "opentok_subscriber";
}
});
Related
I have 2 webcam connected to my pc. I am using this library https://github.com/infusion/jQuery-webcam.
I am able to view the webcam no problem and I can also change to other camera by right clicking, and the Adobe Flash Player will popup where I can select other camera.
Following this website:
http://sshilko.com/examples/jQuery-AS3-Webcam/example.html
The example shown in that website, it can change the camera by selecting from the dropdownlist.
But my code stucks at
debug: function (type, string) {
if (type == 'error') {
$("#lblCameraList").html(string);
} else {
$("#lblCameraList").html('');
}
},
Error says "No camera mode present, falling back...".
Below that code is another code
cameraEnabled: function () {
this.debug('notice', 'Camera enabled');
var cameraApi = this;
if (cameraApi.isCameraEnabled) {
return;
} else {
cameraApi.isCameraEnabled = true;
}
var cams = cameraApi.getCameraList();
for (var i in cams) {
$("#cboCamera").append("<asp:ListItem Value='" + i + "'>" + cams[i] + "</asp:ListItem>");
}
$("#cboCamera").change(function () {
var success = cameraApi.setCamera($(this).val());
if (!success) {
//webcam.debug('error', 'Unable to select camera');
console.log("Failed to set camera");
} else {
//webcam.debug('notice', 'Camera Changed');
console.log("Success set camera");
}
});
The program wont event enter this cameraEnabled because of the error.
Any helps?
Problem solved. I followed exactly from this website http://sshilko.com/examples/jQuery-AS3-Webcam/example.html
The error was i was not using the same javascript file as the website.
I have a Button
d3.select("#updatebutton").on("click", function(e) {
try{
$.get('any url', function(data) {
alert('Any Alert Message');
window.location.href = window.location.href;
});
}
catch (e) {
alert('Error: ' + e);
}
}
where i want to do certain actions on the button click event:
app.get('any url', function(req, res, next) {
try{
anyfunction();
}
catch(e) {
alert('Error');
}
});
It is working fine on normal web browser, however if I open my webpage on a mobile device, it seems that the click event is never called and nothing happens. Is this a jQuery Problem or am I missing something?
The Code is running on a node.js Server.
Hope anyone can help.
UPDATE:
I'm using jade as rendering-engine for HTML. My Button looks like the following:
div#updatebutton
i.fa.fa-repeat.fa-lg
| 'some description'
Try with touchstart event.
UPDATE
Please check.
var myButton = d3.select("#updatebutton");
myButton.on("touchstart", onDown);
function onDown() {
alert("Work");
try{
$.get('any url', function(data) {
alert('Any Alert Message');
window.location.href = window.location.href;
});
}
catch (e) {
alert('Error: ' + e);
}
}
You can detect user device using navigator object. Refer this
If device is touch enabled then use touchstart/touchend events or use click events for desktops(click events should work in mobile browsers too, can not guess the reason by going through the provided code)
Try this:
function is_touch_device() {
return (('ontouchstart' in window) || (navigator.MaxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0));
}
var myButton = d3.select("#updatebutton");
var myEvent = is_touch_device() ? 'touchend' : 'click';
myButton.on(myEvent, onDown);
function onDown() {
$.get('any url', function(data) {
alert('Any Alert Message');
window.location.reload(); //better way to reload the page
}).fail(function(error) {
console.log(error);
});
}
I have the following code in javascript:
function ConnectWebSocket() {
if ("WebSocket" in window) {
myWebsocket = new WebSocket("wss://myserver/mychannel");
myWebsocket.onmessage = function(evt) {
alert("onmessage");
}
myWebsocket.onopen = function() {
alert("onopen");
myWebsocket.send("msg0");
myWebsocket.send("msg1");
myWebsocket.send("msg2");
}
myWebsocket.onclose = function() {
alert("onclose");
ConnectWebSocket();
}
} else {
// Do something if there is no websockets support
}
}
ConnectWebSocket();
The problem is that in Firefox, the connection is closed after sending the messages, and reopened due to the command on the onclose event. If I try to send only one message on onopen, the connection keeps opened, but if I try to send more than one message, the connection shut down. This issue appears only in Firefox, not in Chrome, not in IE, not in Safari.
Can someone help me? In other browsers like IE or Chrome, once the connection is created, it keep opened until I leave the page. I have the 40.0.3v of Firefox
Try this example:
var url = "ws://echo.websocket.org";
if (!window.WebSocket) alert("WebSocket not supported by this browser");
var myWebSocket = {
connect: function () {
var location = url
this._ws = new WebSocket(location);
this._ws.onopen = this._onopen;
this._ws.onmessage = this._onmessage;
this._ws.onclose = this._onclose;
this._ws.onerror = this._onerror;
},
_onopen: function () {
console.debug("WebSocket Connected");
},
_onmessage: function (message) {
console.debug("Message Recieved: " + message.data);
},
_onclose: function () {
console.debug("WebSocket Closed");
kiosk.connect();
},
_onerror: function (e) {
console.debug("Error occured: " + e);
},
_send: function (message) {
console.debug("Message Send: " + message);
if (this._ws) this._ws.send(message);
}
};
myWebSocket.connect();
setInterval(function() {
myWebSocket._send('msg1');
}, 5000);
Here is a JSFidlle
It may be that your support var is not behaving as you expect. The following code works in FireFox without closing the connection:
function ConnectWebSocket() {
if ("WebSocket" in window) {
myWebsocket = new WebSocket("ws://echo.websocket.org/");
myWebsocket.onmessage = function (evt) {
alert("onmessage");
}
myWebsocket.onopen = function () {
alert("onopen");
myWebsocket.send("a test message");
}
myWebsocket.onclose = function () {
alert("onclose");
ConnectWebSocket();
}
} else {
// Do something if there is no websockets support
}
}
ConnectWebSocket();
Example Fiddle
You can use the tool on Websocket.org to make sure websockets are
working correctly in your browser.
Or (although your issue is with FF) you can use the steps listed
here to debug websockets.
Try it.
var WS = window.WebSocket || window.MozWebSocket;
if (WS){
var websocket = new WS("wss://myserver/mychannel");
}
I would like to find out if the user's device has an attached camera and microphone, and if so, has permissions been granted to get the audio and video stream using Javascript. I want to make this check to be made across Chrome and Firefox at the very least. What's a consistent API for this?
Live Demo:
https://www.webrtc-experiment.com/DetectRTC/
If user didn't allow webcam and/or microphone, then media-devices will be having "NULL" value for the "label" attribute. Above page will show this message: "Please invoke getUserMedia once."
PS. You can type "DetectRTC.MediaDevices" in the Chrome Console developers tool.
Note: It works only in Chrome. Firefox isn't supporting similar API yet. (Updated: Firefox supports as well)
Updated at Dec 16, 2015
Note: Following code snippet works both in Chrome and Firefox.
if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
// Firefox 38+ seems having support of enumerateDevicesx
navigator.enumerateDevices = function(callback) {
navigator.mediaDevices.enumerateDevices().then(callback);
};
}
var MediaDevices = [];
var isHTTPs = location.protocol === 'https:';
var canEnumerate = false;
if (typeof MediaStreamTrack !== 'undefined' && 'getSources' in MediaStreamTrack) {
canEnumerate = true;
} else if (navigator.mediaDevices && !!navigator.mediaDevices.enumerateDevices) {
canEnumerate = true;
}
var hasMicrophone = false;
var hasSpeakers = false;
var hasWebcam = false;
var isMicrophoneAlreadyCaptured = false;
var isWebcamAlreadyCaptured = false;
function checkDeviceSupport(callback) {
if (!canEnumerate) {
return;
}
if (!navigator.enumerateDevices && window.MediaStreamTrack && window.MediaStreamTrack.getSources) {
navigator.enumerateDevices = window.MediaStreamTrack.getSources.bind(window.MediaStreamTrack);
}
if (!navigator.enumerateDevices && navigator.enumerateDevices) {
navigator.enumerateDevices = navigator.enumerateDevices.bind(navigator);
}
if (!navigator.enumerateDevices) {
if (callback) {
callback();
}
return;
}
MediaDevices = [];
navigator.enumerateDevices(function(devices) {
devices.forEach(function(_device) {
var device = {};
for (var d in _device) {
device[d] = _device[d];
}
if (device.kind === 'audio') {
device.kind = 'audioinput';
}
if (device.kind === 'video') {
device.kind = 'videoinput';
}
var skip;
MediaDevices.forEach(function(d) {
if (d.id === device.id && d.kind === device.kind) {
skip = true;
}
});
if (skip) {
return;
}
if (!device.deviceId) {
device.deviceId = device.id;
}
if (!device.id) {
device.id = device.deviceId;
}
if (!device.label) {
device.label = 'Please invoke getUserMedia once.';
if (!isHTTPs) {
device.label = 'HTTPs is required to get label of this ' + device.kind + ' device.';
}
} else {
if (device.kind === 'videoinput' && !isWebcamAlreadyCaptured) {
isWebcamAlreadyCaptured = true;
}
if (device.kind === 'audioinput' && !isMicrophoneAlreadyCaptured) {
isMicrophoneAlreadyCaptured = true;
}
}
if (device.kind === 'audioinput') {
hasMicrophone = true;
}
if (device.kind === 'audiooutput') {
hasSpeakers = true;
}
if (device.kind === 'videoinput') {
hasWebcam = true;
}
// there is no 'videoouput' in the spec.
MediaDevices.push(device);
});
if (callback) {
callback();
}
});
}
// check for microphone/camera support!
checkDeviceSupport(function() {
document.write('hasWebCam: ', hasWebcam, '<br>');
document.write('hasMicrophone: ', hasMicrophone, '<br>');
document.write('isMicrophoneAlreadyCaptured: ', isMicrophoneAlreadyCaptured, '<br>');
document.write('isWebcamAlreadyCaptured: ', isWebcamAlreadyCaptured, '<br>');
});
Now you can use navigator.permissions also to check permissions already exist
navigator.permissions.query({ name: "camera" }).then(res => {
if(res.state == "granted"){
// has permission
}
});
See MDN for more info.
But note that support is patchy as of Jan 2021:
Chrome supports navigator.permissions.query as of Chrome 43+, and supports querying camera and microphone permissions, at least as of Chrome 87+.
Firefox supports navigator.permissions.query as of Firefox 46+, but does not support querying camera or microphone permissions as of Firefox 84.
Safari does not even support navigator.permissions.query.
Yes it is quite possible to detect whether a microphone and a camera is available after granting the permission.
Using the old API:
navigator.getUserMedia({ audio: true, video: true}, function (stream) {
if (stream.getVideoTracks().length > 0 && stream.getAudioTracks().length > 0) {
//code for when none of the devices are available
} else {
// code for when both devices are available
}
}, function (error) {
// code for when there is an error
});
Using the newer, promise-based API:
navigator.mediaDevices.getUserMedia({ audio: true, video: true})
.then(function (stream) {
if (stream.getVideoTracks().length > 0 && stream.getAudioTracks().length > 0){
//code for when none of the devices are available
} else {
// code for when both devices are available
}
})
.catch(function (error) {
// code for when there is an error
});
1)You should be using Media Recorder and understand promise
2)Check if browser support the API enumerateDevices
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
console.log("This browser does not support the API yet");
}
3) Check if user has conected audio and camera, the only values are "videoinput", "audioinput" or "audiooutput" DeviceInfo.kind
let checking=["audioinput","videoinput"];
let onlyHas=[];
navigator.mediaDevices.enumerateDevices()
.then((devices)=> {
let haveAllDevices=true;
devices.forEach((device)=>{
onlyHas.push(device.kind);
if(!(device.kind==checking[0] || device.kind==checking[1])){
haveAllDevices=false;
}
});
//do something about ...
})
.catch(function(err) {
console.log(err.name + ": " + err.message);
});
4)Permissions are reused,it means that if user already has denied permission then when you call getUserMedia the bowser won't prompt anything and will reject the promise promise throwing an error of type DOMException, otherwise it will resolve the promise.
When the promise rejects it can be many reasons read, one of then is when user has denied access, when this happens it will throw an DOMException of type NotAllowedError, so for now we are only interested in this error.
If you read DOMException you can see you can acces DOMException.name, this is the one that you should be compared, so:
let constraints={audio:true,video:true};
navigator.mediaDevices.getUserMedia(constraints)
.then((stream)=>{.....})
.catch((err)=>
{if(err.name=="NotAllowedError"){console.log("User has denied accessed")}
});
PS: About cross browser compatibility MediaRecorder as for today 09/06/2018 it is only supported in chrome and firefox, and the brothers IE and IOS don't
https://caniuse.com/#search=MediaRecorder
This function checks if the user have audio and video access:
checkMediaAccess = async() => {
navigator.mediaDevices.enumerateDevices().then( devices =>
devices.forEach( device => {
if(device.kind == 'audioinput' && device.label) console.log('Has Audio Access');
if(device.kind == 'videoinput' && device.label) console.log('Has Video Access');
}
));
}
You can use the MediaStreamTrack which represent a media stream, then you can use its getSources method as explained here: html5rocks
If you don't get any media sources then your client hasn't a webcam.
It's not supported by firefox.
Please try my simple cross browser code.
Attention!!! Use https protocol for open web page with my code! Please go to demo
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>Web camera</h1>
<video autoplay></video>
<script>
function errorMessage(message, e) {
console.error(message, typeof e == 'undefined' ? '' : e);
//alert(message);
}
if (location.protocol === 'https:') {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({ audio: true, video: true }, function (stream) {
document.querySelector('video').src = window.URL.createObjectURL(stream);
var mediaStreamTrack = stream.getVideoTracks()[0];
if (typeof mediaStreamTrack != "undefined") {
mediaStreamTrack.onended = function () {//for Chrome.
errorMessage('Your webcam is busy!')
}
} else errorMessage('Permission denied!');
}, function (e) {
var message;
switch (e.name) {
case 'NotFoundError':
case 'DevicesNotFoundError':
message = 'Please setup your webcam first.';
break;
case 'SourceUnavailableError':
message = 'Your webcam is busy';
break;
case 'PermissionDeniedError':
case 'SecurityError':
message = 'Permission denied!';
break;
default: errorMessage('Reeeejected!', e);
return;
}
errorMessage(message);
});
} else errorMessage('Uncompatible browser!');
} else errorMessage('Use https protocol for open this page.')
</script>
</body>
</html>
I have tested it into follow browsers:
Windows 10
Chrome 52
Edge 25
Firefox 47
IE11 Uncompatible browser!
Opera 39
Safari 5 Uncompatible browser!
Android
Chrome 52
Firefox 48
Opera 37
everyone I'm creating an "Object" to manage all information about my socket connection but I've some problems about browser compatibilities
$(document).ready(function(){
socket.connect();
socket.connection.onopen = function(){
console.log('Connected '+ socket.connection.readyState);
//Show 1 for every browser
};
socket.connection.onmessage = function(event){
console.log('Some message '+event.data);
//Firefox / Chrome Fine
//Midori/Opera doesnt show this message (console)
};
});
var socket ={
dataConnection: {
url:"myURL",
param:"myParam"
},
connection: "",
connect: function(){
try{
this.connection = new WebSocket(this.dataConnection.url+"/"+this.dataConnection.param);
}catch(error){
console.log('Something wrong ' + error.message);
}
}
};
I don't understand Wy It works fine (FF and Chrome), Can you give an advice?