Professor Zero
Professor Zero

Reputation: 35

javascript redirect only pc users not mobile

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

Upvotes: 0

Views: 1043

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65808

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";
}

Upvotes: 1

Adam Azad
Adam Azad

Reputation: 11297

Use ! logical not operator to alter the statement

if(!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 // Desktop / pc
}

Upvotes: 1

Related Questions