I have built a parallax intro for a clients site - due to the limited budget the animation will only work on higher end browsers, IOS and ie9.
Therefore I need to create a detection script in the sites homepage which will detect the following
IF:
ie9/ firefox / chrome/ safari - stay on current site
IOS - Go to IOS version
Android - Skip to main site
IE8 and below - skip to main site
I have carried out 'is mobile' detections in the past with PHP - but the above is pretty specific so I'm not sure how to approach it.. The main site is aspx, so I could make the animation page into a aspx page also and use server side detection, or look at Javascript/jquery options or plugins - or a combination of both..?
Can anyone recommend a good solution?
In hopes of not getting into browser detection / feauture detection argument blah blah blah, http://www.quirksmode.org/js/detect.html has a good script to handle this
Try with following code, uses the navigator object::
var ua = navigator.userAgent;
if(navigator.appName == "Netscape"){ //for Firefox, Safari and Chrome
//do nothing, stay on this page.
return;
}
else if(navigator.appName == 'Microsoft Internet Explorer'){
//check for version
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null){
version = parseFloat( RegExp.$1 );
}
if(version >= 9.0){
//do nothing, stay on this page.
return;
}
else{
//redirect to the site for lower IE versions.
}
}
else if(ua.match(/Android/i)){
//code for skipping to Android version
}
else if(ua.match(/iPhone/i)){
//code for skipping to iPhone version
}
else if(ua.match(/iPad/i)){
//code for skipping to iPad version
}
there is a JQuery object $.browser which could give you what you need in javascript here is the api call.
On the Server Side there is a .net Request.Browser object also here is the MSDN Api for it.
Related
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;
}
I've tried out the solutions proposed here:
Cross Browser Flash Detection in Javascript
but they do not seem to work in Chrome v29.0.1547 on Android v4.1.2
I'm using the code in Drupal, hence I had to escape the ' , but I do not think there is an issue with that, however here is the complete code that I've tried:
$onloadjssndsetup3 = 'jQuery(document).ready(function($){
var isFlashExists = swfobject.getFlashPlayerVersion().major !== 0 ? true : false ;
if (isFlashExists == false) {
$("#main").before("aa");};
});
';
drupal_add_js($onloadjssndsetup3, 'inline');
This code adds the "aa" to the page.
I've also tried this other code:
$onloadjssndsetup3 = 'jQuery(document).ready(function($){
var isFlashExists = swfobject.hasFlashPlayerVersion(\'1\') ? true : false ;
if (isFlashExists) {
$("#main").before("aa");};
});
';
drupal_add_js($onloadjssndsetup3, 'inline');
but it doesn't work either, the "aa" is not added in this case.
the funny part is that it's an Samsung Galaxy SIII the smart phone that I'm trying on, and flash is working on it with no prolem, it's just that I can't make the swfobject report it properly, it reports that flash is not installed.
Am I doing something wrong?
On Win8 on IE , FF it detects it properly.
Most probably there is no solution to this issue, people answered on the previous thread, but obviously it doesn't work on all versions of Android, or maybe it's just the Android version v4.1.2 that is a bit wired...
I'm in the process of building a single mobile-optimized page with a contact-form and a receipt-page.
In our CMS we have a "desktop"-page with the same content, but I am not able to edit the desktop-page in terms of CSS, redirect or anything of the sorts.
The mobile-page is going to be used for a mobile-only campaign. However, I'd like to make sure, that should someone end up on the page from a desktop or a tablet, they'd be redirected to the desktop-version instead.
I've seen scripts of this sort:
<script type="text/javascript">
<!--
if (screen.width <= 699) {
document.location = "mobile.html";
}
//-->
</script>
But hey, mobiles have much higher resolutions these days, so making a reverse "if >=699 then redirect to desktop-site", probably won't work for me, will it? Samsung Galaxy s 3 almost has desktop resolution...
Using media queries is not really an option, seeing as this is two seperate sites (due to the old, rigid CMS).
So how do I redirect non-mobile and tablet users, while anyone on any mobile phone stays on the mobile-page page.
Please note - our servers don't run PHP and I cannot makes changes in server-side files. I need something JavaScript-ish I think.
here is a nice snippet that I use:
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i) ? true : false;
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i) ? true : false;
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i) ? true : false;
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
}
};
if (isMobile.any()) {
window.location = 'http://m.example.org';
}
I never really understood why so many people are looking for detecting "mobile devices". As front-end dev, you actually shouldn't are about the such called mobile devices as much as you're looking for browser-vendors and that is, not at all.
Why not checking for capabilities instead? Create a dynamic, progressive enhanced web-app which adapts to its current environment. Doesn't matter if that means touch-events or standard-events, screen resolution or other things.
However, if you persist on checking for browsers or devices, your best shot still is the userAgent string located in the navigator object, see #MihaiIorga's answer.
However, we should really try to avoid those "sepparation" in entirely different apps/projects for browser and/or devices. I understand the point if there already is a more or less "huge" application or site which needs to work proberly on another device in a very short amount of time, but on the long run you won't do much good with that practice. Many more devices / browsers (versions) / {things I can't think of} will get released in the future.
// To Check if Mobile browser,then redirect to mobile version website otherwise open web url.
//alert(navigator.userAgent);
// userAgent gives all info related to browser,os,device info
var index = navigator.appVersion.indexOf("Mobile");
if (index>0)
{ window.location.href='[mobile page url]'; }
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
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"); }