Detect if Android or iPhone and show something based on results - javascript

I'm trying to display a link based whether a website visitor is use an Android or iPhone mobile device. But I can't seem to get this code I've been working on to actually work. Any help is much appreciated.
I've search Stackoverflow and Google for a solution and all I can find are partial solutions - but nothing I have found has proved successful as of yet.
Here's the code I've been trying to make work.
<p class="iphone">iphoneclass</p>
<p class="android">androidclass</p>
$(document).ready(function() {
if (navigator.userAgent.match(/(iPhone|iPad)/)) {
$('.android').hide();
}
if (navigator.userAgent.match(/(Android)/)) {
$('.iphone').hide();
}
});

here how i check for users' device. maybe this works for you too.
const userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (/android/i.test(userAgent)) {
// android users
$('.iphone').hide();
} else if (/iphone/i.test(userAgent) || /ipad/i.test(userAgent)) {
// ios users
$('.android').hide();
}

A simple but inelegant way is to try and detect the user-agent string.
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/userAgent
So, something like
const agent = window.navigator.userAgent;
And then you can try and match it against the device by doing some sort of regex search
https://deviceatlas.com/blog/mobile-browser-user-agent-strings

Related

How to detect if webkitSpeechRecognition actually works in a browser

Edge claims to support webkitSpeechRecognition, but it doesn't work (discussion here, doesn't work on websites meant for testing, like this mozilla one, with the error "Error occurred in recognition: language-not-supported" despite my US english UI).
How can I detect if webkitSpeechRecognition is actually supported? I tried to filter out Edge by looking at the user agent, but it shows up as Chrome, and I'd prefer to just use feature detection rather than looking at the user agent anyway. I'd like to check this without requesting microphone permission (if I did request microphone permission, I'd have to wait for them to accept, and then see the language-not-supported error). Is there a simple way to check this, similar to just checking the value of window["webkitSpeechRecognition"] (which is defined in Edge, despite not working)?
If you want to check the support for webkitSpeechRecognition then you can refer to the JS code example below.
if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)
{
console.log("speech recognition API supported");
}
else
{
console.log("speech recognition API not supported")
}
Output in MS Edge 88.0.705.56:
However, if you directly try to make a test using webkitSpeechRecognition then it will not work.
It looks like this feature is currently under development and to use it we need to enable it by passing the command line arguments.
I suggest you refer to the steps below.
Create a shortcut of the Edge chromium-browser.
Right-click the shortcut file and go to Properties.
Under Shortcut tab, in the Target textbox, add --enable-features=msSpeechRecognition after the msedge.exe path. Make sure to add 1 space between the path and command-line argument.
It should look like below.
Click on the OK button to close the properties window.
Launch the Edge browser via shortcut and visit any sample code example for SpeechRecognition. Here I am making a test with this example.
Output in MS Edge 88.0.705.56:
In addition, it's useful to check for errors (as shown in the above example source code, see below, https://www.google.com/intl/en/chrome/demos/speech.html): for instance audio might be disabled if not on a https website.
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
start_img.src = '/intl/en/chrome/assets/common/images/content/mic.gif';
showInfo('info_no_speech');
ignore_onend = true;
}
if (event.error == 'audio-capture') {
start_img.src = '/intl/en/chrome/assets/common/images/content/mic.gif';
showInfo('info_no_microphone');
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
showInfo('info_blocked');
} else {
showInfo('info_denied');
}
ignore_onend = true;
}
};

One button -- 3 App stores -- how to redirect the user to the appropriate appstore?

I am wanting to create a simple button which redirects mobile users to the appropriate app store link depending on which mobile os they are running (ios, android or wp8) - or if not on a mobile then offers to send an email containing the appropriate link...Any ideas?
Well... This is actually pretty straightforward. To begin with, you must detect the device the user is currently using by means of their user agent string. And then use jQuery to simply set the href attribute of the anchor element correctly. The following code illustrates.
var operatingSystem, userAgentString = navigator.userAgent;
var link = $("#store");
if (userAgentString.indexOf("iPhone") > -1 || userAgentString.indexOf("iPod") > -1 || userAgentString.indexOf("iPad") > -1) {
operatingSystem = "iOS";
link.attr("href", "http://store.apple.com/us/browse/app");
} else if (/Android/.test(userAgentString)) {
operatingSystem = "Android";
link.attr("href", "https://play.google.com/store/apps?hl=en");
} else if (/Windows Phone/.test(userAgentString)) {
operatingSystem = "Windows Phone";
link.attr("href", "http://www.windowsphone.com/en-us/store");
}
http://jsfiddle.net/5g0zqm0s/
Check the user agent to determine what OS is being run and based on result route link appropriately.
Using php, you can detect which mobile device the user is on. There are several plugins for this. You could then echo out the href of the link accordingly. Sorry, cant comment. Spent too much bounty!

What is the best way to detect websocket support using Javascript?

I'm trying to use Javascript to detect if a web browser supports websockets, but using only feature-based detection, I'm getting false positives, so I added a user agent test to throw out Android devices instead, which I'm not happy about. I have a Samsung Galaxy Tab 2, and here's my detection code:
var isSupported = (("WebSocket" in window && window.WebSocket != undefined) ||
("MozWebSocket" in window));
/* This line exists because my Galaxy Tab 2 would otherwise appear to have support. */
if (isSupported && navigator.userAgent.indexOf("Android") > 0)
isSupported = false;
if (isSupported)
document.write("Your browser supports websockets");
else
document.write("Your browser does not support websockets");
This code seems to work with IE, Firefox, Safari (including iPhone/iPad), and Chrome. However, the feature-based check is returning true when I use the default browser of my Samsung Galaxy Tab 2, which is incorrect because that browser does not actually support websockets. Furthermore, I don't know how many other Android devices have this same issue, so at the moment, this is the best solution I'm aware of for detection.
Is there a better way to detect websocket support other than what I'm doing? I do realize that workarounds exist for Android, such as using a different browser, which means my user agent detection code as-is would not be a good thing. My goal is to not have to rely on the user agent in the first place.
Any suggestions?
This is the shortest solution and is used by Modernizr. Simply add this to your code
supportsWebSockets = 'WebSocket' in window || 'MozWebSocket' in window;
then you can use it by running
if (supportsWebSockets) {
// run web socket code
}
I think the Modernizr library is what you are looking for: http://modernizr.com/
Once you include the library on your page, you can use a simple check like:
if(Modernizr.websockets){
// socket to me baby
}
This page comes on top in google search.
In year 2016 cutting the mustard for modern WebSockets implementation (no prefixes such as MozWebSocket) would be
if (
'WebSocket' in window && window.WebSocket.CLOSING === 2
) {
// supported
}
http://www.w3.org/TR/websockets/#the-websocket-interface
after reading #gzost's response.. I started tinkering.. since nothing else can properly detect WS's on my android phone... even websocket.org says i have it, but then fails to connect.
Anyways, try this workaround.. seems to properly detect it on/off with chrome, FF, safari and the default android browser.
var has_ws=0;
function checkWebSocket(){
try{
websocket = new WebSocket("ws:websocket.org");
websocket.close('');
}catch(e){ //throws code 15 if has socket to me babies
has_ws=1;
}
}
$(document).ready(function(){
checkWebSocket();
});
None of the above answers by itself was sufficient in my tests. The following code seems to be working fine:
function nll( o ) { return CS.undefined === typeof o || null === o; }
// ...
function check_ws_object() {
try {
var websocket = new WebSocket( "wss://echo.websocket.org" );
return true;
} catch ( e ) { ; }
return false;
}
//
function check_support() {
if ( !( WebSocket in window ) ) {
if ( nll( window.WebSocket) ) {
if ( !this.check_ws_object() ) {
alert( "This browser doesn't support HTML5 Web Sockets!" );
return false;
}
}
}
return true;
},
The above tests are sorted, so that the faster ones come first.

Detect if client is iPhone, if so display a specific div

I'm tuning the mobile view of my website and I was wondering, if there a way to detect if client is an iPhone, and if so display <div id="iphone-bar"></div> ?
Can't find a way to do this...
You can check your user agent string:
Returns the user agent string for the current browser.
Ref: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.userAgent
Like:
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
$('#iphone-bar').show();
}
If you want to check mobile browsers in general use http://detectmobilebrowsers.com/ and get the regexp to match them.
Try
<script>
var iPhone= ( navigator.userAgent.match(/iPhone)/g) ? true : false );
if( iPhone ) {
document.getElementById('iphone-bar').style.display = 'block'
}
</script>
Use below code:
function isiPhone() {
return (navigator.platform.indexOf("iPhone") != -1);
}
Then, use it as below:
if(isiPhone()) {
//handle iPhone code
}

iOS iPad and iPhone user agent does not work in Phonegap application

I´m trying to detect if the device is an iPad or an iPhone, but it isn´t working with the emulator. It works if i test it in the safari browser on the iPad. Is there a difference?
It always uses the "else" for iphone..
this i my code:
var isiPad = navigator.userAgent.match(/iPad/i) != null;
$(document).ready(function(){
if(isiPad)
{
window.location.replace("tab/indexTabStart.html");
}
else {
window.location.replace("smart/indexSmartStart.html");
}
});
please help me thanks!
You can try the api provided by phonegap.
try using device.model
device.model - Get the device's model name.
example:
var string = device.model;
Description
The device.model returns the name of the device's model or product. The value is set by the device manufacturer and may be different across versions of the same product.
for full documentation here:
http://docs.phonegap.com/en/3.0.0/cordova_device_device.md.html#Device

Categories