Search code examples
javascriptjquerybrowserwebkit

Detect webkit browser in javascript?


EDITED: I actually used PHP to detect and create a local variable with php tags.

if ( strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'webkit')) {
    $is_webkit = "true";
}

How do I detect if the browser is webkit based? (Google Chrome, newer Opera, safari);

I've tried this:

var isWebkit = (window.webkitURL != null);
if(isWebkit){
    alert("i am a webkit based browser!");
}

Doesn't work for safari


Solution

  • The basic of them all is this: w3school JS.

    Code:

    <script>  
    txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";  
    txt+= "<p>Browser Name: " + navigator.appName + "</p>";  
    txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";  
    txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";  
    txt+= "<p>Platform: " + navigator.platform + "</p>";  
    txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";  
    txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";  
    document.getElementById("example").innerHTML=txt;  
    </script>
    

    But this is not sure about -webkit-.

    Here is a fiddle for that, I mean a fiddle for the -webkit- browser alert! (For Chrome, Safari only; Opera 15+ not supported yet!) jsfiddle.

    Here is a jQuery code, for this! try this:

    $(document).ready(function(){
    
        /* Get browser */
        $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
    
        /* Detect Chrome */
        if($.browser.chrome){
            /* Do something for Chrome at this point */
            /* Finally, if it is Chrome then jQuery thinks it's 
               Safari so we have to tell it isn't */
            $.browser.safari = false;
        }
    
        /* Detect Safari */
        if($.browser.safari){
            /* Do something for Safari */
        }
    
    });
    

    This will show a popup, as soon as the windows loads!

    The best and easy and readable solution would be this:

    $.browser.chrome = $.browser.webkit && !!window.chrome;  
    $.browser.safari = $.browser.webkit && !window.chrome;  
    if ($.browser.chrome) alert("You are using Chrome!");  
    if ($.browser.safari) alert("You are using Safari!");
    

    These were the basics, that I found on some sites:

    1. w3schools.com
    2. stackoverflow (I used this site to find fiddles.