Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how do I use browser detection JS to run specific HTML based on detection result?

Status
Not open for further replies.

zoldos

Technical User
Nov 5, 2008
90
US
I found this code snippet via a Google search and it is exactly what I need, but I'm not sure how to implement it. I'd like to use it to run specific code depending on browser. For example, if Firefox, then simply use linked Javascript, if IE/Chrome, then I'd like to use alternate code (HTML and JS).

How can this be done?

Code:
var isOpera = !!window.opera || navigator.userAgent.indexOf('Opera') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome;                          // Chrome 1+
var isIE = /*@cc_on!@*/false;                            // At least IE6

document.write('isFirefox: ' + isFirefox + '<br>');
document.write('isChrome: ' + isChrome + '<br>');
document.write('isSafari: ' + isSafari + '<br>');
document.write('isOpera: ' + isOpera + '<br>');
document.write('isIE: ' + isIE + '<br>');
 
use if else constructs

Code:
if(isFirefox){

...do stuff
}
if(is chrome){
etc
}
 
Okay thanks! But how do I execute standard HTML and/or more JS after the "if" statements?
 
execute HTML? not sure what you mean.

and as for js you just do what you need between in the if statement. just like you would with any language
 
In other words, I can do this for example:

Code:
if(isFirefox){

      {* SHOW MY NOTIFICATIONS POPUP *}
{if $notifys[1] != 0}
		<div align="center">
		<span class='updatesboxdivider'>-=</span><span class='updatesbox'>Updates & Notifications</span><span class='updatesboxdivider'>=-</span>
        <div class='newupdates' id='newupdates'>
          <div class='newupdates_content'>
            <a style='color:#000000;' href='javascript:void(0);' class='newupdates' onClick="TB_show('{lang_print id=1198}', '#TB_inline?height=150&width=300&inlineId=newupdates_popup', '', './images/trans.gif');">{assign var="notify_total" value=$notifys[0]|@count}{lang_sprintf id=1019 1="<span id='notify_total'>`$notify_total`</span>"}</a></b>
	      <!--&nbsp;&nbsp; 
	      <a style='color:#000000;' href='javascript:void(0);' class='newupdates' onClick="hideNewupdates();" title='Remove Notification'>X</a>-->
	  </div>
        </div>
		</div>


{* HIDDEN POPUP BOX IF USER HAS NEW UPDATES *}

  <div style='display: none;' id='newupdates_popup'>
    <div style='margin-top: 10px;align:right;'>
      {assign var="notifyscount" value=$notifys[0]|@count}
      {lang_sprintf id=1199 1="<span id='notifyscount'>`$notifyscount`</span>"}
    </div>
    {section name=notify_loop loop=$notifys[0]}
      <div style='font-weight: bold; padding-top: 5px;' id='notify_{$notifys[0][notify_loop].notifytype_id}_{$notifys[0][notify_loop].notify_grouped}'>
       <!--<a title='Remove Notification' style='color:#000000;' href='javascript:void(0);' onClick="parent.deleteNotify('{$notifys[0][notify_loop].notifytype_id}', '{$notifys[0][notify_loop].notify_grouped}');">X</a>--><img src='./images/icons/{$notifys[0][notify_loop].notify_icon}' border='0' style='border: none; margin: 0px 5px 0px 5px; display: inline; vertical-align: middle;' class='icon'><a href="{$notifys[0][notify_loop].notify_url}">{lang_sprintf id=$notifys[0][notify_loop].notify_desc 1=$notifys[0][notify_loop].notify_total 2=$notifys[0][notify_loop].notify_text[0]}</a></div>
    {/section}
    </div>
  </div>

<script type="text/javascript" src="./include/js/newupdates_addon.js"></script>

{/if}

}
if(is chrome){

{* HIDDEN POPUP BOX IF USER HAS NEW UPDATES *}

  <div style='display: none;' id='newupdates_popup'>
    <div style='margin-top: 10px;align:right;'>
      {assign var="notifyscount" value=$notifys[0]|@count}
      {lang_sprintf id=1199 1="<span id='notifyscount'>`$notifyscount`</span>"}
    </div>
    {section name=notify_loop loop=$notifys[0]}
      <div style='font-weight: bold; padding-top: 5px;' id='notify_{$notifys[0][notify_loop].notifytype_id}_{$notifys[0][notify_loop].notify_grouped}'>
        <a title='Remove Notification' style='color:#000000;' href='javascript:void(0);' onClick="parent.deleteNotify('{$notifys[0][notify_loop].notifytype_id}', '{$notifys[0][notify_loop].notify_grouped}');">X</a> <img src='./images/icons/{$notifys[0][notify_loop].notify_icon}' border='0' style='border: none; margin: 0px 5px 0px 5px; display: inline; vertical-align: middle;' class='icon'><a href="{$notifys[0][notify_loop].notify_url}">{lang_sprintf id=$notifys[0][notify_loop].notify_desc 1=$notifys[0][notify_loop].notify_total 2=$notifys[0][notify_loop].notify_text[0]}</a></div>
    {/section}
    </div>
  </div>

{literal}
<script type='text/javascript'>
<!--

var se_show_newupdates = new Hash.Cookie('se_show_newupdates', {duration: 3600});

{/literal}{if $notifys[1] != 0}{literal}
  window.addEvent('domready', function() {
    if(se_show_newupdates.get('total') < {/literal}{$notifys[1]}{literal}) {
      se_show_newupdates.set('total', '0');
      $('newupdates').style.display='block';
    }
  });

{/literal}{/if}{literal}
var notify_count = {/literal}{$notifys[1]}{literal};
function deleteNotify(notifytype_id, notify_grouped) {
  $('ajaxframe').src = 'misc_js.php?task=notify_delete&notifytype_id='+notifytype_id+'&notify_grouped='+notify_grouped;
}
function deleteNotifyConfirm(notifytype_id, notify_grouped) {
  $("TB_window").getElements('div[id=notify_'+notifytype_id+'_'+notify_grouped+']').each(function(el) { if(el.id == 'notify_'+notifytype_id+'_'+notify_grouped) { el.style.display = 'none'; notify_count--; }});
  $('newupdates_popup').getElements('div[id=notify_'+notifytype_id+'_'+notify_grouped+']').each(function(el) { if(el.id == 'notify_'+notifytype_id+'_'+notify_grouped) { el.style.display = 'none'; }});
  $('notify_total').innerHTML = notify_count;
  $("TB_window").getElements('span[id=notifyscount]').each(function(el) { if(el.id == 'notifyscount') { el.innerHTML = notify_count; }});
  if(notify_count == 0) {
    TB_remove();
    $('newupdates').style.display = 'none';
  }
}
function hideNewupdates() {
  $('newupdates').fade('out');
  se_show_newupdates.set('total', '{/literal}{$notifys[1]}{literal}');
}
function SwapOut(id1) {
  $(id1).src = Rollarrow1.src;
  return true;
}
function SwapBack(id1) {
  $(id1).src = Rollarrow0.src;
  return true;
}
//-->
</script>
{/literal}
{/if}

}

Which is basically what I'm trying to do...
 
I'm sure you can find a way to include different HTML depending on client side if else statements but it's a terrible idea. if you are looking to change the content based on browser then either pull the content using ajax or better still sniff the browser server side and decide which content to show at that point (and this is the standard way of doing it).
 
Why is it a terrible idea? I've already tested the code in my first post and it does exactly what I need: basic detection of IE, Chrome, and Firefox...
 
because it is not straightforward to serve different content from within the page. you will have to send _all_ content to the script and then determine which of it to display. This is inefficient in terms of bandwidth, as a starter.

the alternative, as said, is to use ajax, which is more efficient in terms of bandwidth, but less efficient in terms of resources.

basically I can see no reason to do browser detection for CONTENT on the client rather than the server. There is no logical use case that would indicate that doing so would be a good idea.

using browser detection to determine how to do something in javascript, or css, is a slightly different case. However mostly for determining javascript approaches, it would be better to use a pre-stress-tested architecture like jQuery.


 
Okay, gotcha. Honestly tho, when I further tested it, the mod made my web host's CPU spike quite a bit, and it's gonna take a lot of coding to get it working. I may just forget it, and not mess with what already works with all browsers. :)
 
the mod made my web host's CPU spike quite a bit, and it's gonna take a lot of coding to get it working

ummmm ... what mod? a client-side mod cannot effect the server. and if you have a mod that browser sniffs I have no idea what that would be.

I assume this is linked to your other questions and thus you are using php as a server side language. To sniff in php do the following:

Code:
function getBrowsecap(){
	$fileName = realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'browscap.ini';
	if(is_file($fileName)):
		if ( filemtime($fileName) < (time() + (7 * 24 * 60 * 60))):
			return $fileName;
		endif;
	endif;
	file_put_contents($fileName, file_get_contents('[URL unfurl="true"]http://tempdownloads.browserscap.com/stream.asp?Full_PHP_BrowscapINI'));[/URL]
	return $fileName;
}

function getBrowser(){
	$browscap = getBrowsecap();
	ini_set('browscap', $browscap);
	$bits = get_browser();
	return $bits->browser;
}

function isBrowser( $browser ){
	$browser = ucfirst(strtolower($browser));
	return getBrowser() == $browser;
}

you can either test the browser using isBrowser('Firefox') (etc) or test the value directly by addressing getBrowser();
 
All I know is that the mod uses AJAX and was pinging my host's server repeatedly, and the CPU spiked. As soon as I disabled the mod, the CPU went back to normal.

Yeah the backbone code is PHP.

I don't know enough about PHP/JS to implement this anyway, and as I said, as is, it seems to really hit the CPU hard, so I decided it might not be a good idea to use it in the first place.
 
it is definitely a good idea never to use code that you did not write yourself, or if written by a third party, that you have not disassembled and fully understood each component before use; or where the above is impossible (i.e. compiled C code) then you should first look for a very large community of users that guarantees sufficient revenue to the author to keep supporting the software (e.g. Microsoft Office).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top