Friday, August 26, 2011

Safari User Agent Detection in JavaScript

Here's a quick snippit for detecting if a browser is Safari version 4 or 5. It works for both desktop and mobile (iPhone, iPod, iPad) versions.


function detectSafari45()
{
  var safariRegEx = /Mozilla\/5\.0 \([^\)]*\) AppleWebKit\/\d+\.\d+(\.\d+)? \(KHTML, like Gecko\) Version\/[45]\.\d+\.\d+( Mobile\/\w*)? Safari\/\d+\.\d+(\.\d+)?/i
  var match = safariRegEx.exec(navigator.userAgent);

  if (match !== null && match.length > 0)
  {
    return true;
  }
  return false;
}

No comments: