I have a script that will detect iPhone/iPad and Android devices, but having trouble singling out Desktop/Laptop devices. When viewing the page on an iPhone/iPad, it triggers an alert for "iDevice" first, then an alert for "Desktop". I need to be able to show a different form, based on what platform the user is viewing the page on (iPhone/iPad, Android, Windows Phone, Desktop/Laptop (non mobile devices)). I'm not trying to target resolution, I'm trying to target PLATFORM.
HTML
<div class="iDevice">iDevice</div>
<div class="android-view">Android Device</div>
<div class="desktop">Desktop</div>
Javascript
$("#email").hide();
$(".desktop").hide();
$(".iDevice").hide();
$(".android-device").hide();
$('#checkbox').change(function () {
$('#email').slideToggle();
});
if((navigator.platform === 'iPhone') || (navigator.platform === 'iPad')){
alert("iDevice");
$(".iDevice").show();
$(".android-view").hide();
$(".desktop").hide();
}
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
alert("Android");
$(".iDevice").hide();
$(".android-view").show();
$(".desktop").hide();
}
else if ((navigator.platform != 'iPhone') || (navigator.platform != 'iPad' ) || (isAndroid === false)){
alert("Desktop");
$(".desktop").show();
$(".iDevice").hide();
$(".android-view").hide();
}
JSFIDDLE: LINK
Unless you have a specific need to show content based directly on the device, you should practice Responsive Design. The idea is to style your content for different screen sizes, layouts, or whatever, with CSS and, if need be, Media Queries. Additionally, if you need to have your JavaScript perform different actions based on API availability, you should use a Feature Detection library such as has.js or Modernizr.
That being said though, if you still want to pursue displaying content based on device, one glaring problem that I can see is that your if statements are incorrect:
if (navigator.platform === 'iPhone' || 'iPad'){} resolves to 'iPad' which is truthy.
You need to use a compound if statement like:
if ((navigator.platform === 'iPhone') || ((navigator.platform === 'iPad')){}
This goes for all of your other if statements as well.
Another alternative is to use a regex.test() as was done in another question: Detect if device is iOS.
Additionally, trying to navigate the mess that is the userAgent string will drive you mad. Consider reading WebAim's History of the browser user-agent string in order to see why. I mean, unless you enjoy manhandling all the different user agent strings that Microsoft Internet Explorer has put out in order to trick servers into thinking that it isn't actually IE.
I reworked my logic, and was able to separate the forms with the following mix of targeting navigator.platform and navigator.userAgent:
$("#email").hide();
$(".iDevice").hide();
$(".android-device").hide();
$('#checkbox').change(function () {
$('#email').slideToggle();
});
//IF WINDOWS PHONE
if(navigator.userAgent.match("MSIE")){
$(".iDevice").hide();
$(".android-view").show();
$(".desktop").hide();
}
//ELSE IF iPhone/iPad
else if((navigator.platform === 'iPhone') || (navigator.platform === 'iPad')){
$(".iDevice").show();
$(".android-view").hide();
$(".desktop").hide();
}
//ELSE IF DESKTOP (NOT iPhone/iPad/Android/Windows Phone)
else if ((!navigator.userAgent.match("MSIE")) || (navigator.platform !== 'iPhone' || 'iPad' ) && isAndroid === false){
$(".desktop").show();
$(".iDevice").hide();
$(".android-view").hide();
}
//IF IS ANDROID
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
$(".iDevice").hide();
$(".android-view").show();
$(".desktop").hide();
}
Related
I just want to check if the decive, which is using my website, is on a mobile or any other device. It's a quick question with a quick answer I hope.
If you are trying to see if the user's device is mobile, the MDN docs advises to look for the property maxTouchPoints in the navigator (or browser) object and see if the value is > 0.
In the past this used to be done with User Agent Sniffing (Read more here), i.e going through the user-agent header sent by the browser into the navigator.userAgent property to see if it contains certain keywords. This method however has limitations and may not always tell the right kind of device the user is on because many devices today support different browsers and features and vice versa.
Using User Agent Sniffing (Not recommended today, should be used only as a fallback)
var hasTouchScreen = false;
var UA = navigator.userAgent;
hasTouchScreen = (
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
);
if (hasTouchScreen) {
// Device is likely mobile, so do stuff for mobile devices here.
}
Check using maxTouchPoints property and if > 0 in navigator object (MDN Docs Recommended)
var hasTouchScreen = false;
if ("maxTouchPoints" in navigator) {
hasTouchScreen = navigator.maxTouchPoints > 0;
}
if (hasTouchScreen) {
// Device is likely mobile, so do stuff for mobile devices here.
}
Be aware, that not all browsers may support that specification, so the navigator object may not have the property maxTouchPoints or some mobile devices may have large screens and some desktop devices may have small touch-screens or some people may use smart TVs and so on. So a better way to do this check would be to combine the snippet above with some fallbacks:
Better way to detect mobile devices using a combination of previous method and fallbacks (Most Robust Method, MDN Docs Recommended)
var hasTouchScreen = false;
if ("maxTouchPoints" in navigator) {
hasTouchScreen = navigator.maxTouchPoints > 0;
} else if ("msMaxTouchPoints" in navigator) {
hasTouchScreen = navigator.msMaxTouchPoints > 0;
} else {
var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
if (mQ && mQ.media === "(pointer:coarse)") {
hasTouchScreen = !!mQ.matches;
} else if ('orientation' in window) {
hasTouchScreen = true; // deprecated, but good fallback
} else {
// Only as a last resort, fall back to user agent sniffing
var UA = navigator.userAgent;
hasTouchScreen = (
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
);
}
}
if (hasTouchScreen)
// Do something here.
}
Read more about browser detection using the user agent and the recommended way for mobile device detection here (For the recommended method for mobile device detection, look under the "Mobile device detection" subheading).
Just use this condition in javascript:
if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)){
//do your stuff here
}
I am trying to use javascript to apply a certain style to the pages based on which browser the user is using. I can detect all of the browsers except for IE/Edge. In my code snippet I am just trying to detect IE/Edge and apply the style.
Here is my code:
var bodyStyle = document.querySelector("#bodyArea");
if((navigator.userAgent.indexOf("Edge") != -1 ) || (!!document.documentMode == true ))
{
alert("asdf");
bodyStyle.style.paddingTop = "500px";
}
else
{
bodyStyle.style.paddingTop = "300px";
}
When I put an alert in the else section it gives me an alert, but it doesn't work on the if part. So I think my problem is occurring when I try to detect IE/Edge. Or if it lay elsewhere, let me know. If anyone has any feedback, it will be greatly appreciated. Thanks in advance!
You can use this custom script to detect IE/Edge:
if (/MSIE 10/i.test(navigator.userAgent)) {
// this is internet explorer 10
window.alert('isIE10');
}
if(/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)){
// this is internet explorer 9 and 11
window.location = 'pages/core/ie.htm';
}
if (/Edge\/12./i.test(navigator.userAgent)){
// this is Microsoft Edge
window.alert('Microsoft Edge');
}
Check out this page for the latest IE and Edge user agent strings: https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
I am trying to detect if the user is navigating my website from safari browser on the iphone using jquery / javascript.
I am able to detect the IOS Environment using the user agent string
/iphone/i.test(navigator.userAgent.toLowerCase())
But this detects the Apple Webkit Environment i.e. it is same for all the browsers on the device. Can anyone suggest any different approach.
UPDATED:
Try this, for detecting Safari browser in an iPhone:
var isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/);
It identifies Safari 3.0+ and distinguishes it from Chrome.
JsFiddle
Since the other answer doesn't include detection of an iPhone, including that part.
var isIphone = /(iPhone)/i.test(navigator.userAgent);
var isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/);
if(isIphone && isSafari){
//do something
}
If you want to detect a particular iOS version and above, say iOS 7.0 and above then you can use the below code. It detects iOS version 7-19(for upcoming versions).
var isIphone= /(iPhone)*(OS ([7-9]|1[0-9])_)/i.test(navigator.userAgent);
var isFirefox = navigator.userAgent.indexOf("FxiOS") != -1;
var isChrome = navigator.userAgent.indexOf("CriOS") != -1;
var isEdge = navigator.userAgent.indexOf("EdgiOS") != -1;
var isOpera = navigator.userAgent.indexOf("OPT") != -1;
if (!isFirefox && !isChrome && !isEdge && !isOpera){
console.log("Only display in Safari")
} else {
console.log("Only display in Firefox/Chrome/Edge/Opera")
}
Hi, this way worked for me to detect only safari in ios mobile. The value FxiOs, CriOs, etc, I get from the userAgent value.
it's easy to detect the Android device, but I am having trouble detecting ONLY the Android native browser. Problem is the Dolphin browser has an almost identical user-agent string, and I'd like a way to know if they are using the native browser or not..
Is this possible?
you simply need to test a few parts of the user agent string in order to make sure you have the default android browser:
var nua = navigator.userAgent;
var is_android = (nua.indexOf('Mozilla/5.0') > -1 && nua.indexOf('Android ') > -1 && nua.indexOf('AppleWebKit') > -1);
you can use the following to ensure that you do not match chrome within android, although on a lot of devices now, chrome is being used as the default browser.
var nua = navigator.userAgent;
var is_android = ((nua.indexOf('Mozilla/5.0') > -1 && nua.indexOf('Android ') > -1 && nua.indexOf('AppleWebKit') > -1) && !(nua.indexOf('Chrome') > -1));
EDIT:
If you want to protect against case sensitivity, you can use the following:
var nua = navigator.userAgent.toLowerCase();
var is_android = ((nua.indexOf('mozilla/5.0') > -1 && nua.indexOf('android ') > -1 && nua.indexOf('applewebkit') > -1) && !(nua.indexOf('chrome') > -1));
I think you are searching for this:
Android native browser not updated above version 534.30 so you can filter to the version and
Android UA string combination (above we can presume its a Chrome browser)
Here's my sample JavaScript code:
(If you need specific styling I would add a class to the body with the following JS snippet)
var defectAndroid = $window.navigator && $window.navigator.userAgent.indexOf('534.30') > 0 && $window.navigator.userAgent.toLowerCase().match(/android/);
if (defectAndroid) {
// sample code specific for your Android Stock browser
}
(Some Android devices reporting 'android' that's why we need the lower case conversation)
On a Galaxy S3, I found that both Chrome and the native browser had 'AppleWebkit' so I took that piece out of my conditional statement. I also added Version as that only appears in the native browser is seems. It works for me as
var ua = navigator.userAgent;
var isAndroidNative = ((ua.indexOf('Mozilla/5.0') > -1) && (ua.indexOf('Android') > -1) && !(ua.indexOf('Chrome') > -1) && (ua.indexOf('Version') > -1))
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
// Do something!
// Redirect to Android-site?
window.location = 'http://android.davidwalsh.name';
}
You can do this with Javascript and the useragent feature. What u need to do is to make 2 If-requests:
First you detect the device type:
If android, ios, mobile, ipad, iphone
Take this setting
Now you make as much as u need if-requests or a case-request to detect the type of browser
If chrome, firefox, safari and so on
Take this setting
Thats it in the theory :)
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