How can I check webRTC datachannel compatibility using JavaScript in client side? - javascript

WebRTC datachannel works only in Firefox nightly. How can I check it in client side?
Code is shown as follows;
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
if (ffversion>=5)
document.write("You're using FF 5.x or above")
else if (ffversion>=4)
document.write("You're using FF 4.x or above")
else if (ffversion>=3)
document.write("You're using FF 3.x or above")
else if (ffversion>=2)
document.write("You're using FF 2.x")
else if (ffversion>=1)
document.write("You're using FF 1.x")
}
else
document.write("n/a")

You can simply test if the browser currently supports the features you're going to use. For example:
if (!window.mozRTCPeerConnection)
// error, browser doesn't support it
If you're interested, here an interesting article: Hello Chrome, it’s Firefox calling!
You basically can implement the same feature in Chrome just using webkit prefix instead of moz.

There's a Chrome RTCDataChannel demo now at simpl.info/dc.
This isn't very robust or complete, but you could create a webkitRTCPeerConnection object and then check if it has a createDataChannel member:
try { // or if (webkitRTCPeerConnection) {...}
var pc = new webkitRTCPeerConnection(null);
if (pc && pc.createDataChannel) {
var dc = pc.createDataChannel("sendDataChannel", {reliable: false});
if (!!dc) {
// doSomething()
}
}
} catch (e) {
// try some other instantiation
}

Check the webrtcsupport package. It seems to be cross-browser (Chrome & FF).
https://www.npmjs.org/package/webrtcsupport
If you don't wanna use the NPM package, the main logic can be found here.
https://github.com/HenrikJoreteg/webrtcsupport/blob/master/index-browser.js

Using JavaScript
var prefix;
var version;
if (window.mozRTCPeerConnection || navigator.mozGetUserMedia) {
prefix = 'moz';
version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
} else if (window.webkitRTCPeerConnection || navigator.webkitGetUserMedia) {
prefix = 'webkit';
version = navigator.userAgent.match(/Chrom(e|ium)/) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
}
if(prefix == 'moz' || prefix == 'webkit' && version > 41){
console.log("Browser Support WebRTC")
} else {
console.log("This Browser Not Support WebRTC")
}

The top answer is not right.
if (window.RTCDataChannel) {
// the browser support dataChannel
} else {
// the browser does not support dataChannel
}
If browser support RTCPeerConnection, it not means also support for RTCDataChannel。Such as Edge, createDataChannel on instance of RTCPeerConnection will throw an exception.

Surprised no one mentions checking the prototype.
You can check if createDataChannel exists by doing this:
if (!window.RTCPeerConnection.prototype.createDataChannel) {
// Data Channels not supported
}

I just figured out. Thanks for all your help.
http://mozilla.github.com/webrtc-landing/

Another package that checks for WebRTC support is DetectRTC https://github.com/muaz-khan/DetectRTC

Related

Detect if page is loaded inside WKWebView in JavaScript

How can I reliably detect using javascript that a page is loaded inside a WKWebView? I'd like to be able to detect these scenarios:
iOS & WKWebView
iOS & Safari
not iOS
There is a similar question about UIWebView here. But it's quite old and I'm not sure if same still applies to WKWebView.
The accepted answer doesn't work as tested using the WKWebView vs UIWebView app
As the article mentions, the only HTML5 feature difference is IndexedDB support. So I'd go for a more reliable pattern with:
if (navigator.platform.substr(0,2) === 'iP'){
//iOS (iPhone, iPod or iPad)
var lte9 = /constructor/i.test(window.HTMLElement);
var nav = window.navigator, ua = nav.userAgent, idb = !!window.indexedDB;
if (ua.indexOf('Safari') !== -1 && ua.indexOf('Version') !== -1 && !nav.standalone){
//Safari (WKWebView/Nitro since 6+)
} else if ((!idb && lte9) || !window.statusbar.visible) {
//UIWebView
} else if ((window.webkit && window.webkit.messageHandlers) || !lte9 || idb){
//WKWebView
}
}
You may ask: Why not using the UserAgent? That's because Android browsers use it as settings! So, we should never trust any UAs. Only browser features and property checks as such.
Also I noticed that the QuickTime plugin was always loaded as part of Older Safari and other Browsers in UIWebView. But the plugin is no longer present in WKWebView. So you can use the QuickTime plugin presence as an extra check.
9/23/16 Edit: I adjusted the code for Safari 10 which no longer allowed the sole idb check to be reliable, as mentioned by #xmnboy. To discard Safari 10, it checks for the old webkit engine bug, which only applied until Safari 9.2; and i use a window.statusbar.visible fallback which appears to be a reliable indicator signal after a few comparison tests between iOS 9 and 10. (please check though)
Given the change in behavior to the UIWebView that was introduced by Apple in iOS 10, here's a new answer that combines the original response by #Justin-Michael and the follow-up favorite by #hexalys.
var isWKWebView = false ;
if( navigator.platform.substr(0,2) === 'iP' ) { // iOS detected
if( window.webkit && window.webkit.messageHandlers ) {
isWKWebView = true ;
}
}
It turns out that Justin's answer was really the better feature detection mechanism, because it works for both iOS 9 and iOS 10.
No telling what happens when we get to iOS 11. :-)
Qualification: this test will work if you are using the official Cordova WKWebView plugin to build your webview app, because that plugin does initialize the addScriptMessageHandler method, as noted by #hexalys in the comments to this post. That mechanism is being used by Cordova to define a new JS to native bridge when the WKWebView plugin is present.
Search for addScriptMessageHandler in that plugin repo and see the very end of the ios-wkwebview-exec.js file in that repo for some implementation details (or search for the string window.webkit.messageHandlers in that file).
In iOS, you could add this code to establish communication between javascript and objective-c:
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *controller = [[WKUserContentController alloc] init];
[controller addScriptMessageHandler:self name:#"javascript_observer"];
configuration.userContentController = controller;
...
webview = [[WKWebView alloc] initWithFrame:... configuration: configuration];
In javascript, you could test the connection like this:
if ( window.webkit != undefined ){
//javascript is running in webview
}
It seems that because the latest iOS Chrome uses WKWebView as a rendering engine, Chrome is detected as WKWebView.
ua.indexOf('CriOS') !== -1
will helps to distinguish Chrome from WKWebView in App.
You can check for the existence of window.webkit.messageHandlers which WKWebKit uses to receive messages from JavaScript. If it exists, you're inside a WKWebView.
That combined with a simple user agent check should do the trick:
var iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
var isWKWebView = false;
if (window.webkit && window.webkit.messageHandlers) {
isWKWebView = true;
}

Check the real availability of IndexedDB in Firefox

I have to check the IndexedDB availability for the Firefox browser only. Currently I do the trick with this :
var IDB_SUPPORTED = 'indexedDB' in window;
Simple. But if I disable IndexedDB in about:config (with the dom.indexedDB.enabled parameter), IDB_SUPPORTED is still true.
How can I check the real availability of IndexedDB in Firefox without any third-party library like Modernizr?
This did it for me:
try { window.indexedDB } catch (err) { IDB_SUPPORTED = false; }

What headers or javascript do I add to the HTML to reject older browsers?

Developing a frontend realtime javascript application, we have decided to drop support for older browsers since it takes too much effort to support them.
What header or javascript should we add in the HTML, so that when they hit the URL, I can redirect them a page to obtain newer browsers before proceeding to our application?
you can use following properties of navigator object
navigator.appCodeName
navigator.appName
navigator.appVersion
navigator.cookieEnabled
navigator.platform
navigator.userAgent
you can also use jquery browser object
http://api.jquery.com/jQuery.browser/
The better option is to use feature detection. For example, to test if a browser has geolocation support, you can use the following:
if (navigator.geolocation)
{
// interact with geolocation features
}
If you insist on using browser detection instead, however, you can use the following to detect if the browser is using IE 8 or below:
function getInternetExplorerVersion()
// Returns the version of Windows Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
var ver = getInternetExplorerVersion(); // example: 8.0
var belowIE8 = ver <= 8.0;
Found here: http://www.mkyong.com/javascript/how-to-detect-ie-version-using-javascript/
If you want to determine this based on a particular JavaScript version, see below code (untested):
<script language="javascript1.5">
var supported = true;
</script>
<script>
if ('undefined' === typeof supported) {
alert('not at least 1.5 supported');
}
It's still better to do feature detection though, as that ties in better with what you're going to use it for.

javascript user agent redirect by browser version number

We have a chat program that works with only a couple of browsers right now. So, I'm inserting a user agent redirect to manage the messaging to inform the user why they can't chat with their unsupported browser.
The issue I'm having is only Firefox 3.1 and under, for example, is supported for FireFox., but my custom script below is enabling all Firefox versions compatible. What's the solution to have only Firefox 3.1 be compatible?
Note: I don't plan to send them to the actual browser websites as seen in my example. I just put those URLs in for example purposes only. I plan to have custom redirect pages with friendly messaging on them...
Demo of existing code:
http://jsfiddle.net/evanmoore/4xr77/
Code is below:
<script type="text/javascript">
if ((navigator.userAgent.indexOf('Firefox') != -1) || (navigator.userAgent.indexOf('MSIE') != -1))
{
// Your browser is supported for live chat
document.location = "http://www.livechatinc.com/";
}
else if(navigator.userAgent.indexOf("Safari") != -1)
{
// Your Safari browser is not supported for live chat
window.location = "http://www.apple.com";
}
else if(navigator.userAgent.indexOf("Chrome") != -1)
{
// Your Chrome browser is not supported for live chat
window.location = "http://www.google.com/chrome";
}
else
{ // All others... Your browser is not supported for live chat
window.location = "http://www.gofetch.com";
}
</script>
Based on Asad's comment, I found the different browser strings here which gave me the ability to control the version number like so... I think this should do the trick!
if ((navigator.userAgent.indexOf('Firefox/3.1') != -1)
Try checking if the functionality exists, not the version of the browser.
e.g. if (typeof foo != 'undefined') will check if foo exists
You can find more info here

What is the correct way to detect Opera using jQuery?

Amazon.com recently updated their javascript, and it's causing problems with some Opera browsers.
Their browser detection code looks like so, but it's faulty:
function sitbReaderIsCompatibleBrowser() {
if (typeof(jQuery) == 'undefined') {
return false;
} else {
var version = jQuery.browser.version || "0";
var splitVersion = version.split('.');
return (
(jQuery.browser.msie && splitVersion[0] >= 6) // IE 6 and higher
|| (jQuery.browser.mozilla && (
(splitVersion[0] == 1 && splitVersion[1] >= 8) // Firefox 2 and higher
|| (splitVersion[0] >= 2)
))
|| (jQuery.browser.safari && splitVersion[0] >= 500) // Safari 5 and higher
|| (jQuery.browser.opera && splitVersion[0] >= 9) // Opera 5 and higher
);
}
}
Nothing obviously wrong jumps out at me with this code, but I've never used jQuery before so I don't know.
Even though this code looks like it's attempting to let Opera users through, when I visit the page with Opera 9.64 I get an "unsupported browser" message. If I change Opera's settings to report itself as Firefox, the page works perfectly! With that in mind, I'm pretty sure it's a problem with the script and not the browser.
Any jQuery experts have a suggestion?
You can replicate the behavior by visiting any book on Amazon and clicking the "look inside this book" link.
Prior to jQuery 1.3, you could use jQuery.browser:
if( $.browser.opera ){
alert( "You're using Opera version "+$.browser.version+"!" );
}
From version 1.3, you should use jQuery.support instead.
Main reason for this is that should should avoid checking for browsers, as features may change from version to version, making your code obsolete in no time.
You should always try to use feature detection instead. This will allow you to see if current browser supports the feature you're trying to use, regardless the browser brand, version, etc.
There is a special window.opera object which is present in all Opera 5+ browsers. So something as simple as:
if (window.opera && window.opera.buildNumber) {
// we are in Opera
}
would be enough.
I check for Opera like this:
if (/Opera/.test (navigator.userAgent)) // do something
Why would you want jQuery?
It is much better to detect javascript capabilities rather than browser userAgent.
ie DOM, XmlHttpRequest, eventing model (event.target vs event.srcElement), ActiveX, Java etc
By focusing on the API functions that you will require, rather than a target browser you will create a more robust set of scripts, and inevitably less special casing.
This link here at opera will probably tell you more
A very simple way from Opera themselves:
if (window.opera) {
//this browser is Opera
}
Source: http://my.opera.com/community/openweb/idopera/
The main reason why Amazon fails on Opera is because the send different code from the server side already... If you visit the same page with Firefox and then save that page and reopen it in Opera it works fine...
But they promised to fix that sometime in January...
I think this way is the best
if ( window.opera.version() == 12) {
}
This example check if opera version is 12. Very useful when I have problems with font-face in Opera.
I don't know for sure ( i never really check for opera anyway) but if the built-in jQuery functionality doesn't detect opera, may be a bug with the jQuery which needs to be fixed. I would suspect if that's the case, it should get resolved fairly quickly.
In current HTML5 times, you can also check for browser features instead often.
if (!window.FormData) { alert("xmlhttprequest L2 FormData interface not available"); }

Categories

Resources