How to know if a mobile device is showing desktop? - javascript

I have seen very many questions asking how to detect if a device is mobile or not. Generally, they fall into 3 categories:
Check the screen size/viewport
Check the User Agent
Use a library, such as Modernizr to work around browser capabilities.
After implementing what I could, I still run across a situation which I have never seen asked or addressed; On many mobile browsers, there is a "Request desktop site" (Chrome) "Desktop Mode" (Dolphin) or "Desktop View" (HTC Sense).
I have chosen strategy #1 above, which works unless the page is viewed in desktop mode. Implementing #2 has drawbacks (spoofing, uncatalogued agents, etc.).
Is there a reliable (cross browser) way to detect Desktop Mode on a mobile browser with Javascript? jQuery or other libraries would be okay, but it should be based upon feature detection, rather than an array of User Agents.

So, Finally I have proven method to detect this. There's little tricky but got Exact Solution.
STEP 1
Install device-uuid Library , ( Here already mentioned. How to install )
<script src="https://raw.githubusercontent.com/biggora/device-uuid/master/lib/device-uuid.min.js"></script>
<script>
var user_configuration = new DeviceUUID().get();
console.log(user_configuration);
</script>
// output
// {"isAuthoritative":true,"isMobile":true,......"resolution":[980,1104],"browser":"Chrome"}
STEP 2
Detect device width
var curr_width = parseInt((window.innerWidth).toFixed());
STEP 3
Now need to compare curr_width with user_configuration.resolution[0] (width)
If both are same then this is normal view and if not then it's "DESKTOP VIEW" . attaching screenshot.
if(curr_width == user_configuration.resolution[0]){
alert("normal_view");
}else{
alert("desktop_view");
}
Screenshot of Desktop Mode ON in mobile browser
Screenshot of Normal mobile view

There is no way for a webpage to detect whether the device is actually a desktop computer or not. When "Request desktop site" is enabled, the phone acts just like a desktop does. One way to check this is to check the OS of the device. However, some phones use windows as their OS, so this won't work on windows phones.

Related

JavaScript - browser detection for iOS/Android touch devices

I have the following JavaScript code that utilises browser detection and navigator.platform property and the navigator.userAgent property of the navigator object. This is used to execute environment/platform specific code based on what device an end user is browsing on.
The issue stemmed from the behaviour of Bootstrap tooltips on Android and iOS devices - the tooltips appears when the user hovers over an <a> element, now touch devices have no concept of hover and do not handle it well (for example on iOS using Safari the tooltips are not able to be dismissed after the first touch, on Android using Chrome the tooltip is visible for a split second). The decision was made that tooltip functionality should not be available to users on mobile devices, as they are not handled well.
The issue is visible here on the <a> elements (a tooltip is intentionally applied to the iOS and Android code blocks to demo issue) used as links with an icon that read 'Disco', 'Bouncy Castles', 'Clowns' etc. (if viewed on a phsyical iOS or Android tablet above 768px): http://fun-booths.co.uk/dev/
HTML (one fragment)
<span class="dec-block hidden-xs">
<span class="promo-details">
<i class ="fa fa-headphones"> </i>
<span class="promo-a-cont">
<a href="http://www.bestdiscointown.co.uk" title="" class="customtooltip" data-original-title="Best Disco in Town offer a professional DJ suitable for any party.">
<span class="dashed"> Disco </span>
</a>
</span>
</span>
JS
As you can see the code says if isOS tests true then don't execute the tooltip JavaScript, the else if statement then checks if isAndroid tests true and again no tooltip JavaScript is executed. Finally an else statement says if the users is on any other system then execute the tooltip JavaScript.
$(document).ready(function(){
var isOS = /iPad|iPhone|iPod/.test(navigator.platform);
var isAndroid = /(android)/i.test(navigator.userAgent);
///////////////////////////////////////// if OS
if (isOS){
///////////////////////////////////////// if Android
} else if(isAndroid){
///////////////////////////////////////// if another system
} else {
toolOptions = {
animation: true,
placement:"top",
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
container:"body"
};
$('.customtooltip').tooltip(toolOptions);
}//end if system
});
I need to increase my understanding of this issue and potential solutions, so please if you can answer my questions.
Is the navigator object a native JavaScript object like the date object is?
If the navigator object is native, then am I correct in saying this is surely built in to all modern web browsers as they have a JavaScript engine? So why is this considered a bad practice?
After performing research on MDN - the navigator.platform property and the navigator.userAgent are stated as:
'This feature has been removed from the Web standards. Though some
browsers may still support it, it is in the process of being dropped.
Do not use it in old or new projects. Pages or Web apps using it may
break at any time.'
and:
Browser identification based on detecting the user agent string is
unreliable and is not recommended, as the user agent string is user
configurable.
Given that this approach of browser detection does not abide by web standards how can I prevent tooltips being displayed to the user on touch devices?
I have tested this on multiple versions of real Android tablets and iOS tablets and this JavaScript fix does work - even though it is bad practice. The popovers do not appear and therefore I consider the issue to be fixed. However are there other touch device scenarios I haven't considered outside of Android and iOS devices.

Calling function if mobile

I'm completely lost when it comes to jQuery/Javascript so apologies in advance. I'm using the MixItUp jQuery filter on a Wordpress site which has the option to show either grid or list view (default), what I'd like to do is set grid as default when visiting the site using a mobile device.
This is what I have at the moment (I've been copying and pasting from around the web so probably not even close):
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
$(document).ready(function(){
$('#Grid').mixitup('toGrid');
});
Any help on this issue would be highly appreciated!
I have messed with detecting if a device is mobile or not a lot in the past and I have found it to be much easier to detect if it is not a mobile device versus detecting if it is a mobile device.
I like the searches you are doing, but you are missing a few like the Nook and Kindle a lot of mobile devices also use the word "mobile" in their user agent. With that said even if you include these in your search you will surely have more that pop up over the next few years. I have found it to be better to detect if it is a desktop or not because there are not new desktop operating systems being added on almost a yearly basis like we are seeing with mobile devices these days. Not only that but I have also found that older Android devices can return mixed results in their user agents.
Here is the bit of code we use to figure out if the device is Windows, Linux, Mac, Facebook, a bot, or a mobile device. We have used and tested this code a lot with all the different devices we have vising our site and it appears to be working correctly for all devices. I hope this helps!
$(document).ready(function(){
if (deviceType() == "Mobile")
$('#Grid').mixitup('toGrid');
});
function deviceType ()
{
var OSName="Mobile";
if (navigator.appVersion.indexOf("Win")!=-1 && navigator.appVersion.indexOf("Phone")===-1) OSName="Windows";
if (navigator.appVersion.indexOf("Macintosh")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1 && navigator.appVersion.indexOf("Android")===-1) OSName="Linux";
if (navigator.appVersion.indexOf("facebook.com")!=-1) OSName="facebook";
if (navigator.appVersion.indexOf("bot")!=-1) OSName="bot";
if (navigator.appVersion.indexOf("Slerp")!=-1) OSName="bot";
return OSName;
}
You want to wrap the "if" statement and function call inside the document ready call. Not the other way around:
$(document).ready(function () {
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent)) {
$('#Grid').mixitup({layoutMode : 'grid'});
}
});

Exclude javascript from being loaded for touch screen devices

I am using tinyscrollbar to replace the standard scrollbars on desktop versions of my web app. The main reason for this is so that i have a consistent and nice design across all desktop browsers. On an android, mobile ios device and windows mobile device i would just want to use the native scroller. This means that i wouldnt want to include my scroller css nor the javascript for it. If anyone has any experience with this it would be very helpful. I worry about windows 8 machines becuase they are desktops and tablets.
for conditionnal loading, I suggest Yepnope, it is the script loader used in Modernizr (so if you use Modernizr, it's probably already there).
Modernizr.load({
test : Modernizr.touch,
nope : 'slick-scroller.js'
});

Flash always on top in Android browser workaround?

I have a website with a simple Flash animation behind some text and semi-transparent images as a background. I have used swfobject to embed it and set wmode opaque to make it display correctly in most browsers.
For browsers without Flash, the user gets a static background image instead and would not know they were missing anything. However, Android users get the flash background on top of everything as per the known issue with how Flash content is rendered in the Android browser making the site unusable.
I have added a crude browser sniff javascript function to the swfobject code to prevent it from loading for any user agent whith 'Mobile' in it:
<script type="text/javascript">
if (navigator.userAgent.indexOf('Mobile') == -1)
{
var flashvars = {};
var params = { wmode: "opaque" };
var attributes = {};
swfobject.embedSWF("Images/Layout/center_flash.swf", "flashBg",
"1004", "502", "9", "false", flashvars, params, attributes);
}
</script>
The only problem I have left is for Android users browsing with 'Mobile View' turned off as the user agent pretends to be a desktop version of Safari (I think). I do not wish to disable the Flash animation for all Safari users. Is there a way of blocking it for just Andriod users - even if they have 'Mobile View' disabled?
Possible ideas include:
detecting the Flash version with JavaScript or Flash. Does Android use specific versions (version numbers) of Flash which are different from the desktop equivalent?
blocking the specific user agents used by Android devices with 'Mobile View' disabled.
Has anyone come up with an effective workaround for this issue?
Your help/input is appreciated!
You can detect android only by checking the userAgent of the browser in your JavaScript
Something like this:
if (navigator.userAgent.toLowerCase().indexOf("android") != -1)
{
// It's android
}
As far as the flash issue itself, I don't know as I never use flash :P
edit
You can also use that technique for other useragents (I.E. iPhone, iPad, safari)
edit2
Sorry, I just went on my android phone and realized the actual setting changes the userAgent to whatever the user picks (desktop/ipad/iphone/safari). That's no good then, I apologize.
Unfortunately, what you are asking is very difficult then. There are no unique identifiers in the android flash version to give you any help. And the fact that android spoofs the userAgent makes it impossibly to detect if they are on mobile or not.
There exist services that can tell you whether a user is on mobile based on their IP.
I'm sorry to say I don't know how fast, reliable, or expensive they are, but if you must determine whether a user is on Android, that's an avenue to consider

Loading JS script for only iOS devices?

I have a jQuery script I'm using on a site to allow fixed position background images on iPhone/iPad/iPod. However it seems to be clashing with another script I am using on the site that enlarges background images full screen. Luckily they're independent of each other, I don't need the clashing background image script to work on iOS devices and vice versa.
Is there a way I can specifically target IOS devices to serve a JS file? I initially thought about using some kind of IF statement and doing it on window size but that started to get a bit complicated and affects other non-IOS devices. It just needs to run something like this...
..."if IOS device then load scroll.js"
I know device/browser sniffing is frowned upon but I can't think of another way around this problem.
You can use the Mobile Safari user agent string to detect mobile safari server-side, see: How do I detect Mobile Safari server side using PHP?
You can also do this in JavaScript:
if(navigator.userAgent.match(/(iPhone|iPod|iPad)/i))
See iPhone & iPod Detection Using JavaScript for more information.
You can use Detect Mobile Browser (it has a library for javascript).
you can also try this
if (navigator.userAgent.match(/like Mac OS X/i)) {
alert('Hi, you\'re browsing from an iOS device.');
}

Categories

Resources