javascript redirect only pc users not mobile - javascript

I am trying to redirect pc users who are using adblock to a certain page.but i dont want to redirect mobile users.
here is my code
<script src="/assets/js/ads.js" type="text/javascript"></script>
//the bait for adblock
<script type="text/javascript">
if(document.getElementById('ElvJCLbfcHDP')){
alert('Blocking Ads: No');
} else {
alert('Blocking Ads: Yes');
}
as you can see this only shows if the ads are blocked or not.but what I want to do is check if users are coming from mobile or PC then redirect only PC adblock users to a certain page and let mobile users use site as it is.
i found this
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// some code..
}
but as u can see it only detects if users is from mobile and then run the code.i want it to check if user is from PC and then run the redirect

Use ! logical not operator to alter the statement
if(!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// Desktop / pc
}

Don't try to redirect based on a test for a device.. You'll spend every moment of your time updating the list and wondering why some devices that are on your list are getting through. navigator.userAgent is notoriously unreliable.
From MDN:
Deprecated This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of
being dropped. Avoid using it and update existing code if possible;
see the compatibility table at the bottom of this page to guide your
decision. Be aware that this feature may cease to work at any time.
The NavigatorID.userAgent read-only property returns the user agent
string for the current browser.
The specification asks browsers to provide as little information via
this field as possible. Never assume that the value of this property
will stay the same in future versions of the same browser. Try not
to use it at all, or only for current and past versions of a
browser. New browsers may start using the same UA, or part of it, as
an older browser: you really have no guarantee that the browser agent
is indeed the one advertised by this property.
Also keep in mind that users of a browser can change the value of this field if they want (UA spoofing).
Typically, a desktop can be rooted out simply by the width of the window (as measured in CSS pixels, not hardware pixels).
if(window.innerWidth > 1280){
location.href = "desktop path";
} else {
location.href = "mobile path";
}

Related

How do we check if a browser's auto-update is enabled through javascript

I want to check form the javascript if a browser's auto-update is enabled.
The reason I want this is that our software supports only a set of Browser versions and we want to alert them if auto-update is on.
Is there any way we can do this?
Abhi
No. Browsers are highly sand-boxed and will give you almost no information about the users system.
You'll instead have to just do something like check the version and alert them if it isn't up-to-date, with maybe some information on how to check if they have auto-updated turned on.
Not sure why you require a set version, but one thing to do is check if the browser supports a specific method (One that your app requires).
If not, tell them to update their browser. This example test if the user has WebSockets:
if (window.WebSocket) {
alert("BROWSER SUPPORTED");
} else {
alert("BROWSER NOT SUPPORTED");
}

How to detect if web app running standalone on Chrome mobile

Chrome mobile has recently added the ability to add to home screen, similar to iOS. This is cool but it doesn't support it as well as iOS - it doesn't support window.navigator.standalone so you can't detect whether you are running as a standalone app.
The reference says:
How can I detect if the app is running as an installed app?
You can’t, directly.
Notice it says "directly". My question is can we do it indirectly? Is there some tricky way to make an educated guess?
This answer comes with a huge delay, but I post it here just for other people who are struggling to find a solution.
Recently Google has implemented the CSS conditional display-mode: standalone, so there are two possible ways to detect if an app is running standalone:
Using CSS:
#media all and (display-mode: standalone) {
/* Here goes the CSS rules that will only apply if app is running standalone */
}
Using both CSS and Javascript:
function isRunningStandalone() {
return (window.matchMedia('(display-mode: standalone)').matches);
}
...
if (isRunningStandalone()) {
/* This code will be executed if app is running standalone */
}
If you need more information, Google Developers has a page dedicated to this topic: https://developers.google.com/web/updates/2015/10/display-mode
iOS and Chrome WebApp behaves different, thats the reason i came to following:
isInWebAppiOS = (window.navigator.standalone === true);
isInWebAppChrome = (window.matchMedia('(display-mode: standalone)').matches);
Same as here: Detect if iOS is using webapp
For the IOS we have window.navigator.standalone property to check..
But for Chrome on Android, it doesn't support this property. Only way to check this is by calculating screen width and height.
Below is the code to check that:
navigator.standalone = navigator.standalone || (screen.height-document.documentElement.clientHeight<40)
I got reference from below link:
Home Screen Web Apps for Android Thanks to Chrome 31
An old question but significantly better solutions available today for Chrome Android.
One of the ways(cleanest IMO). You may add Web App Manifest with a 'start_url' key with a value that adds a query string parameter to your usual homepage.
ex:- if homepage url is https://www.example.com.
in Web App Manifest set
"start_url": "https://www.example.com/?user_mode=app"
Google's guide about Web app manifest:https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
With IOS, localstorage for the standalone and web mode are different. With android KitKat and Chrome, when you save a value in localstorage on the web version, you're able to retrieve it in standalone mode.
So, you just have to save document.documentElement.clientHeight to localstorage when user is browsing the web version (before adding to homescreen). Then, just compare the current value of document.documentElement.clientHeight with localstorage value. If the current value is >, it's standalone mode.
I tried it on several devices.
For Google Chrome (Android) from version 39 onwards with web application manifest (json) and in case, it is a single page application, I use this 'trick':
In the manifest.json I put: "start_url": "standalone.html".
Normally it is (in my case index.html), but from index.html I make an identical clone: standalone.html (or whatever you fancy).
Then, to check, I use Javascript like this:
var locurl = document.location.href;
if (locurl.indexOf("standalone.html") != -1) {
console.log("app is running standalone");
} else {
console.log("app is running in normal browser mode");
}
That works.
It might work too in Google Chrome (mobile) version 31-38 with this meta-tag:
<meta name="application-url" content="http://my.domain.com/standalone.html">.
Not tested, yet.
There is no 'proper' way to do it on Android, hence no API support yet.
The workaround we used in my company -
On first login, store screenheight in localstorage.
By screenHeight i mean document.documentElement.clientHeight before page loads, since then doc grows and its not accurate measure for real available screen height.
Whenever user logs in next time - check current screenheight vs stored - if it becomes bigger, the user has gone fullscreen.
There is no scenario upon which it can become smaller, IF YOU DO store FIRST TIME value for screen height.
Caveat - user that will clean cash.
We chose to ignore that, since most users don't do it or do it relatively rarely, and it will suffice(in our opinion) for some time until there will be API fix for this( hopefully there will be :) )
Option b - check available screenheight vs device screen height, the matchup for a few test devices & browser modes showed some pattern( available height < 70 in webapp) - i strongly believe a wider comparison can get values that will suffice for 90% of devices in 90% cases.
All of this is a workaround, of course, i m not pretending its a solid stable way to get to desired functionality - but for us it worked, so i hope this helps somebody else who fought this bug(cant call missing such crucial api feature other way). Good luck :)
To detect if it's running on MIT AI2 webview:
if (typeof window.AppInventor!="undefined") { return true; }
you have to work with window.navigator.standalone, this API is only works on mobile IOS safari, not event on your macbook or iMac's safari...

Web browser cache clean while javascript development

I am developing javascript code with visual studio. Everything is working wWhen I run the application first, then I changing some value of javascript variable but browser not showing right result. The old result is appearing.
var validationResult =validate("username");
var message = "Welcome, ";
if (validationResult) {
message += username;
$("#status").css("color", "green");
} else {
message += "Guest";
$("#status").css("color", "red");
}
In this example, first run on browser shows right result, but I changed the parameter of validate method as "invalidUser" but result did not changed. I thing browser is caching values. Should I clean browser history every run? Is there any clean solution for Internet Explorer or Firefox?
I think your browser is caching resources, not values. It could also be your server who is caching.
If you have the firebug plugin/extension in firefox you can disable page caching while developing on a per site basis.
Just install firebug, open it, go to the net tab, click options (little arrow on the tab itself), select disable caches.
http://getfirebug.com/
You can force to clean the cache with this javascript
window.location.reload(true);
with a falase argument will do the opposite

Simple javascript detect user's device

I want to add javascript into my template to detect that every time users view my websites with what kind of device (Smartphone, tablet or PC).
Currently, I try to do it with javascript, here it is:
var smartPhone = "smartphone";
var Ipod = "ipod";
var userDevice = navigator.userAgent.toLowerCase();
function DetectPhone()
{
if (userDevice.search(smartPhone) > -1)
return true;
else
windows.location = "/pageforphone.aspx";
}
function DetectIpod()
{
if (userDevice.search(Ipod) > -1)
return true;
else
windows.location = "/pageforpod.aspx";
}
Did I write the codes right? Honestly, no iPhone...
Of course, if these were completed with Php or Asp.net would be better, but is it true that people always turn the javascript off on their palm devices?
Also, i think iphone or ipod or any other tablets are quite similar, is it ok that i use same redev pages for those devices? Actually i am not very understanding what is the differences among them and what should i be aware when i redev my web pages.
The premise of the question, that browser-sniffing is acceptable, is false. You should never engage in browser sniffing, simply because you cannot confidently accomplish what you set out to accomplish. User Agent Strings are not immutable, and are often times changed by plugins installed on the client machine, or by the client themselves (not uncommon, since bad programmers may lock them out of a site based on their UA-String).
Rather than asking what device the user is one, you should instead be asking what functionality is the device capable of. This brings you to feature detection, where you set out to do X, test to see if the user agent is capable of doing X, and then proceed to do or not do X. For instance:
if ( !!document.createElement("video").canPlayType ) {
console.log( "HTML5 Video Supported" );
}
This is more reliable than trying to see if the user is on an iPhone, iPad, Windows Tablet, or HTML5 Enabled Browser. You can use tools like Modernizr to perform a lot of these tests for you - over 40 in fact.
There many mobile devices on the market + each device can have more than one browser installed. I would prefer using some library rather than funding "iPhone" in user agent string (I'm using Android phone with Opera browser myself)
For example:
http://detectmobilebrowsers.mobi/
http://wurfl.sourceforge.net/ - server side, has a large database of devices and features supported
http://modernizr.com - client size JavaScript library, detects which HTML5 features available on browsers (e.g. geolocation API, video, Index DB, local storage, etc.)
Both of them are regularly updated with latest mobile devices released and provide you with information which features are supported on given device
This is how I use javascript to detect iOS devices
<script type="text/javascript">
var agent = navigator.userAgent.toLowerCase();
var isiPhone = ((agent.indexOf('iphone'))!=-1)
if (((agent.indexOf('iphone'))!=-1) {
document.location = "mobile.aspx?device=iphone";
}
if (((agent.indexOf('ipod'))!=-1) {
document.location = "mobile.aspx?device=ipod";
}
if (((agent.indexOf('iPad'))!=-1) {
document.location = "mobile.aspx?device=ipad";
}
</script>

Detecting browsers that don't support onunload/onbeforeunload

Of all the browsers, it seems that only Opera doesn't support onunload/onbeforeunload events. (It's been fifteen years now, Opera!) Solutions for this issue have been covered many times, here for example: onbeforeunload support detection
Unfortunately, as of Opera 11.51, ("onbeforeunload" in window) == true, but the actual onbeforeunload event is never executed!
My web application needs to send data to server when a user leaves the page; I'm using a synchronous ajax request for this. It looks like I have to resort to using a "Save" button somewhere on the page to cover up for Opera issues. However, I don't want this button to confuse users whose browsers are capable of auto-saving through ajax, so I'd really like the button to only show up in Opera.
Is my only choice browser-detection? The problem is, Opera has an option to disguise itself as other browsers anyway.
I can't reproduce your finding that 'onbeforeunload' in window is true in Opera 11.5x. This is the best way to do it and should still work. Are you sure you haven't left in some definition somewhere, e.g. you've written
onbeforeunload = function (){ ... }
later in the same script that does the feature detection? If you do alert(window.onbeforeunload), what do you see? Could you share a link to the page with the problem?
Opera screwed the pooch on this one. I detect for Opera by looking for window.opera and if it exists, I deny Opera what it can't handle.
Using unload is no good I think, because it occurs too late in the game. Sometimes onbeforeunload is the only thing that'll do the trick. Once again, I just look for opera on the window object, and, if it exists, deny it the things it can't do. :)
PPK talks about it here: http://www.quirksmode.org/js/detect.html
For anyone stumbling across this post, this is a code snippet I use for detecting onbeforeunload support and if the browser doesn't support it I switch to onunload (note the use of jquery, obviously not required). In my case I use this code (and a little extra) to check if any AJAX requests are still active and stop the user navigating away. Keep in mind that using onunload isn't ideal because the browser will still navigate away from the page but at least it gives you a chance to warn the user that data might have been lost and they should go back and check.
You'll notice I'm using the isEventSupported() function available at https://github.com/kangax/iseventsupported for cross browser support detecting available events.
// If the browser supports 'onbeforeunload'
if (isEventSupported('beforeunload', window)) {
$(window).on('beforeunload', function(){
return 'This page is still sending or receiving data from our server, if you recently submitted data on this page please wait a little longer before leaving.';
});
}
// The browser doesn't support 'onbeforeunload' (Such as Opera), do the next best thing 'onunload'.
else {
$(window).on('unload', function(){
alert('This page was still sending or receiving data from our server when you navigated away from it, we would recommend navigating back to the page and ensure your data was submitted.');
});
}
See my answer to a similar / duplicated question. Basically, it sets up detection on the very first page on your domain and stores that detection result for all subsequent pages in localStorage. Including working example code.

Categories

Resources