• Stars
    star
    2,388
  • Rank 18,483 (Top 0.4 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 14 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Do some browser detection with Ruby. Includes ActionController integration.

Browser

Tests Gem Gem

Do some browser detection with Ruby. Includes ActionController integration.

Installation

gem install browser

Usage

require "browser"

browser = Browser.new("Some User Agent", accept_language: "en-us")

# General info
browser.bot?
browser.chrome?
browser.chromium_based?
browser.core_media?
browser.duck_duck_go?
browser.edge?                # Newest MS browser
browser.electron?            # Electron Framework
browser.firefox?
browser.full_version
browser.ie?
browser.ie?(6)               # detect specific IE version
browser.ie?([">8", "<10"])   # detect specific IE (IE9).
browser.known?               # has the browser been successfully detected?
browser.unknown?             # the browser wasn't detected.
browser.meta                 # an array with several attributes
browser.name                 # readable browser name
browser.nokia?
browser.opera?
browser.opera_mini?
browser.phantom_js?
browser.quicktime?
browser.safari?
browser.safari_webapp_mode?
browser.samsung_browser?
browser.to_s            # the meta info joined by space
browser.uc_browser?
browser.version         # major version number
browser.webkit?
browser.webkit_full_version
browser.yandex?
browser.wechat?
browser.qq?
browser.weibo?
browser.sputnik?
browser.sougou_browser?

# Get bot info
browser.bot.name
browser.bot.search_engine?
browser.bot?
browser.bot.why? # shows which matcher detected this user agent as a bot.
Browser::Bot.why?(ua)

# Get device info
browser.device
browser.device.id
browser.device.name
browser.device.unknown?
browser.device.blackberry_playbook?
browser.device.console?
browser.device.ipad?
browser.device.iphone?
browser.device.ipod_touch?
browser.device.kindle?
browser.device.kindle_fire?
browser.device.mobile?
browser.device.nintendo?
browser.device.playstation?
browser.device.ps3?
browser.device.ps4?
browser.device.psp?
browser.device.silk?
browser.device.surface?
browser.device.tablet?
browser.device.tv?
browser.device.vita?
browser.device.wii?
browser.device.wiiu?
browser.device.samsung?
browser.device.switch?
browser.device.xbox?
browser.device.xbox_360?
browser.device.xbox_one?

# Get platform info
browser.platform
browser.platform.id
browser.platform.name
browser.platform.version  # e.g. 9 (for iOS9)
browser.platform.adobe_air?
browser.platform.android?
browser.platform.android?(4.2)   # detect Android Jelly Bean 4.2
browser.platform.android_app?     # detect webview in an Android app
browser.platform.android_webview? # alias for android_app?
browser.platform.blackberry?
browser.platform.blackberry?(10) # detect specific BlackBerry version
browser.platform.chrome_os?
browser.platform.firefox_os?
browser.platform.ios?     # detect iOS
browser.platform.ios?(9)  # detect specific iOS version
browser.platform.ios_app?     # detect webview in an iOS app
browser.platform.ios_webview? # alias for ios_app?
browser.platform.linux?
browser.platform.mac?
browser.platform.unknown?
browser.platform.windows10?
browser.platform.windows7?
browser.platform.windows8?
browser.platform.windows8_1?
browser.platform.windows?
browser.platform.windows_mobile?
browser.platform.windows_phone?
browser.platform.windows_rt?
browser.platform.windows_touchscreen_desktop?
browser.platform.windows_vista?
browser.platform.windows_wow64?
browser.platform.windows_x64?
browser.platform.windows_x64_inclusive?
browser.platform.windows_xp?
browser.platform.kai_os?

Aliases

To add aliases like mobile? and tablet? to the base object (e.g browser.mobile?), require the browser/aliases file and extend the Browser::Base object like the following:

require "browser/aliases"
Browser::Base.include(Browser::Aliases)

browser = Browser.new("Some user agent")
browser.mobile? #=> false

What's being detected?

Detecting modern browsers

To detect whether a browser can be considered as modern or not, create a method that abstracts your versioning constraints. The following example will consider any of the following browsers as a modern:

# Expects an Browser instance,
# like in `Browser.new(user_agent, accept_language: language)`.
def modern_browser?(browser)
  [
    browser.chrome?(">= 65"),
    browser.safari?(">= 10"),
    browser.firefox?(">= 52"),
    browser.ie?(">= 11") && !browser.compatibility_view?,
    browser.edge?(">= 15"),
    browser.opera?(">= 50"),
    browser.facebook?
      && browser.safari_webapp_mode?
      && browser.webkit_full_version.to_i >= 602
  ].any?
end

Rails integration

Just add it to the Gemfile.

gem "browser"

This adds a helper method called browser, that inspects your current user agent.

<% if browser.ie?(6) %>
  <p class="disclaimer">You're running an older IE version. Please update it!</p>
<% end %>

If you want to use Browser on your Rails app but don't want to taint your controller, use the following line on your Gemfile:

gem "browser", require: "browser/browser"

Accept Language

Parses the accept-language header from an HTTP request and produces an array of language objects sorted by quality.

browser = Browser.new("Some User Agent", accept_language: "en-us")

browser.accept_language.class
#=> Array

language = browser.accept_language.first

language.code
#=> "en"

language.region
#=> "US"

language.full
#=> "en-US"

language.quality
#=> 1.0

language.name
#=> "English/United States"

Result is always sorted in quality order from highest to lowest. As per the HTTP spec:

  • omitting the quality value implies 1.0.
  • quality value equal to zero means that is not accepted by the client.

Internet Explorer

Internet Explorer has a compatibility view mode that allows newer versions (IE8+) to run as an older version. Browser will always return the navigator version, ignoring the compatibility view version, when defined. If you need to get the engine's version, you have to use Browser#msie_version and Browser#msie_full_version.

So, let's say an user activates compatibility view in a IE11 browser. This is what you'll get:

browser.version
#=> 11

browser.full_version
#=> 11.0

browser.msie_version
#=> 7

browser.msie_full_version
#=> 7.0

browser.compatibility_view?
#=> true

This behavior changed in v1.0.0; previously there wasn't a way of getting the real browser version.

Safari

iOS webviews and web apps aren't detected as Safari anymore, so be aware of that if that's your case. You can use a combination of platform and webkit detection to do whatever you want.

# iPad's Safari running as web app mode.
browser = Browser.new("Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405")

browser.safari?
#=> false

browser.webkit?
#=> true

browser.platform.ios?
#=> true

Bots

The bot detection is quite aggressive. Anything that matches at least one of the following requirements will be considered a bot.

  • Empty user agent string
  • User agent that matches /crawl|fetch|search|monitoring|spider|bot/
  • Any known bot listed under bots.yml

To add custom matchers, you can add a callable object to Browser::Bot.matchers. The following example matches everything that has a externalhit substring on it. The bot name will always be General Bot.

Browser::Bot.matchers << ->(ua, _browser) { ua.match?(/externalhit/i) }

To clear all matchers, including the ones that are bundled, use Browser::Bot.matchers.clear. You can re-add built-in matchers by doing the following:

Browser::Bot.matchers += Browser::Bot.default_matchers

To restore v2's bot detection, remove the following matchers:

Browser::Bot.matchers.delete(Browser::Bot::KeywordMatcher)
Browser::Bot.matchers.delete(Browser::Bot::EmptyUserAgentMatcher)

Middleware

You can use the Browser::Middleware to redirect user agents.

use Browser::Middleware do
  redirect_to "/upgrade" if browser.ie?
end

If you're using Rails, you can use the route helper methods. Just add something like the following to a initializer file (config/initializers/browser.rb).

Rails.configuration.middleware.use Browser::Middleware do
  redirect_to upgrade_path if browser.ie?
end

If you need access to the Rack::Request object (e.g. to exclude a path), you can do so with request.

Rails.configuration.middleware.use Browser::Middleware do
  redirect_to upgrade_path if browser.ie? && request.env["PATH_INFO"] != "/exclude_me"
end

Restrictions

  • User agent has a size limit of 2048 bytes. This can be customized through Browser.user_agent_size_limit=(size).
  • Accept-Language has a size limit of 2048 bytes. This can be customized through Browser.accept_language_size_limit=(size).

If size is not respected, then Browser::Error is raised.

Browser.user_agent_size_limit = 4096
Browser.accept_language_size_limit = 4096

Development

Versioning

This library follows http://semver.org.

Writing code

Once you've made your great commits (include tests, please):

  1. Fork browser
  2. Create a topic branch - git checkout -b my_branch
  3. Push to your branch - git push origin my_branch
  4. Create a pull request
  5. That's it!

Please respect the indentation rules and code style. And use 2 spaces, not tabs. And don't touch the version thing.

Configuring environment

To configure your environment, you must have Ruby and bundler installed. Then run bundle install to install all dependencies.

To run tests, execute ./bin/rake.

Adding new features

Before using your time to code a new feature, open a ticket asking if it makes sense and if it's on this project's scope.

Don't forget to add a new entry to CHANGELOG.md.

Adding a new bot

  1. Add the user agent to test/ua_bots.yml.
  2. Add the readable name to bots.yml. The key must be something that matches the user agent, in lowercased text.
  3. Run tests.

Don't forget to add a new entry to CHANGELOG.md.

Adding a new search engine

  1. Add the user agent to test/ua_search_engines.yml.
  2. Add the same user agent to test/ua_bots.yml.
  3. Add the readable name to search_engines.yml. The key must be something that matches the user agent, in lowercased text.
  4. Run tests.

Don't forget to add a new entry to CHANGELOG.md.

Wrong browser/platform/device detection

If you know how to fix it, follow the "Writing code" above. Open an issue otherwise; make sure you fill in the issue template with all the required information.

Maintainer

Contributors

License

(The MIT License)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

i18n-js

It's a small library to provide the I18n translations on the Javascript. It comes with Rails support.
Ruby
3,702
star
2

kitabu

A framework for creating e-books from Markdown using Ruby. Using the Prince PDF generator, you'll be able to get high quality PDFs. Also supports EPUB, Mobi, Text and HTML generation.
Ruby
659
star
3

recurrence

A simple library that handles recurring events.
Ruby
556
star
4

sparkline

Generate SVG sparklines with JavaScript without any external dependency.
JavaScript
501
star
5

paypal-recurring

PayPal Express Checkout API Client for recurring billing.
Ruby
257
star
6

cpf_cnpj

🇧🇷 Validate, generate and format CPF/CNPJ numbers. Include command-line tools.
Ruby
220
star
7

password_strength

Check password strength against several rules. Includes ActiveRecord/ActiveModel support.
JavaScript
182
star
8

cpf

🇧🇷 Validate, generate and format CPF numbers
TypeScript
161
star
9

pagseguro

Um plugin para o Ruby on Rails que permite utilizar o PagSeguro
Ruby
141
star
10

coupons

Coupons is a Rails engine for creating discount coupons.
Ruby
140
star
11

cpf_cnpj.js

Validate, generate and format CPF/CNPJ numbers
JavaScript
118
star
12

i18n

A small library to provide the I18n translations on the JavaScript.
TypeScript
113
star
13

uptime_checker

Check if your sites are online for $7/mo.
112
star
14

module

Define namespaces as constructor functions (or any object).
JavaScript
105
star
15

qe

A simple interface over several background job libraries like Resque, Sidekiq and DelayedJob.
Ruby
102
star
16

has_calendar

A view helper that creates a calendar using a table. You can easily add events with any content.
Ruby
101
star
17

sinatra-subdomain

Separate routes for subdomains in Sinatra apps
Ruby
96
star
18

validators

Some ActiveModel/ActiveRecord validators
Ruby
96
star
19

dotfiles

My dotfiles
Shell
88
star
20

rack-api

Create web app APIs that respond to one or more formats using an elegant DSL.
Ruby
86
star
21

notifier

Send system notifications on several platforms with a simple and unified API. Currently supports Notification Center, Libnotify, OSD, KDE (Knotify and Kdialog) and Snarl
Ruby
84
star
22

factory_bot-preload

Preload factories (factory_bot) just like fixtures. It will be easy and, probably, faster!
Ruby
83
star
23

cnpj

🇧🇷 Validate, generate and format CNPJ numbers
TypeScript
81
star
24

dispatcher-js

Simple jQuery dispatcher for web apps.
JavaScript
75
star
25

gem-open

Open gems into your favorite editor by running a specific gem command
Ruby
69
star
26

test_notifier

Display system notifications (dbus, growl and snarl) after running tests. It works on Mac OS X, Linux and Windows. Powerful when used with Autotest ZenTest gem for Rails apps.
Ruby
63
star
27

test_squad

Running JavaScript tests on your Rails app, the easy way.
Ruby
56
star
28

vscode-linter

Extension for code linting, all in one package. New linters can be easily added through an extension framework.
TypeScript
56
star
29

has_friends

Add friendship support to Rails apps with this plugin
Ruby
55
star
30

breadcrumbs

Breadcrumbs is a simple Rails plugin that adds a breadcrumbs object to controllers and views.
Ruby
55
star
31

minitest-utils

Some utilities for your Minitest day-to-day usage.
Ruby
52
star
32

photomatic

Your photography is what matters.
Ruby
50
star
33

normalize_attributes

Sometimes you want to normalize data before saving it to the database like down casing e-mails, removing spaces and so on. This Rails plugin allows you to do so in a simple way.
Ruby
49
star
34

burgundy

A simple wrapper for objects (think of Burgundy as a decorator/presenter) in less than 150 lines.
Ruby
49
star
35

ar-uuid

Override migration methods to support UUID columns without having to be explicit about it.
Ruby
46
star
36

rubygems_proxy

Rack app for caching RubyGems files. Very useful in our build server that sometimes fails due to our network or rubygems.org timeout.
Ruby
43
star
37

post_commit

Post commit allows you to notify several services with a simple and elegant DSL. Five services are supported for now: Basecamp, Campfire, FriendFeed, LightHouse and Twitter.
Ruby
42
star
38

permalink

Add permalink support to Rails apps with this plugin
Ruby
40
star
39

keyring-node

Simple encryption-at-rest with key rotation support for Node.js.
JavaScript
39
star
40

superconfig

Access environment variables. Also includes presence validation, type coercion and default values.
Ruby
38
star
41

sublime-better-ruby

Sublime Text Ruby package (snippets, builder, syntax highlight)
Ruby
37
star
42

simple_presenter

A simple presenter/facade/decorator/whatever implementation.
Ruby
33
star
43

voltage

A simple observer implementation on POROs (Plain Old Ruby Object) and ActiveRecord objects.
Ruby
31
star
44

redis-settings

Store application and user settings on Redis. Comes with ActiveRecord support.
Ruby
31
star
45

tokens

Add token support to Rails apps with this plugin
Ruby
31
star
46

boppers

A simple bot framework for individuals.
Ruby
29
star
47

babel-schmooze-sprockets

Add Babel support to sprockets using Schmooze.
JavaScript
29
star
48

streamdeck

A lean framework for developing Elgato Stream Deck plugins.
TypeScript
28
star
49

sublime-text

My SublimeText settings
26
star
50

has_ratings

Add rating support to Rails apps with this plugin
Ruby
25
star
51

commentable

Add comment support to Rails apps with this plugin
Ruby
23
star
52

sinatra-basic-auth

Authentication with BasicAuth that can require different credentials for different realms.
Ruby
23
star
53

rails-routes

Enable config/routes/*.rb on your Rails application.
Ruby
23
star
54

aitch

A simple HTTP client.
Ruby
21
star
55

swiss_knife

Here's my swiss-knife Rails helpers.
Ruby
21
star
56

messages-app

Use alert messages in your README.
HTML
19
star
57

rails-env

Avoid environment detection on Rails
Ruby
19
star
58

defaults

Add default value for ActiveRecord attributes
Ruby
18
star
59

ar-check

Enable PostgreSQL's CHECK constraints on ActiveRecord migrations
Ruby
17
star
60

email_data

This project is a compilation of datasets related to emails. Includes disposable emails, disposable domains, and free email services.
Ruby
17
star
61

sublime-text-screencasts

Screencasts sobre Sublime Text
HTML
17
star
62

simple_auth

SimpleAuth is an authentication library to be used when everything else is just too complicated.
Ruby
17
star
63

attr_keyring

Simple encryption-at-rest with key rotation support for Ruby.
Ruby
17
star
64

has_bookmarks

Add bookmark support to Rails apps with this plugin
Ruby
17
star
65

paginate

Paginate collections using SIZE+1 to determine if there is a next page. Includes ActiveRecord and ActionView support.
Ruby
16
star
66

pry-meta

Meta package that requires several pry extensions.
Ruby
15
star
67

svg_optimizer

Some SVG optimization based on Node's SVGO
Ruby
15
star
68

react-starter-pack

Starter-pack for react + webpack + hot reload + mocha + enzyme + production build
JavaScript
15
star
69

check_files

Check non-reloadable files changes on Rails apps.
Ruby
15
star
70

url_signature

Create and verify signed urls. Supports expiration time.
Ruby
15
star
71

activities

Activities is a gem that enables social activities in ActiveRecord objects.
Ruby
14
star
72

using-es6-with-asset-pipeline-on-ruby-on-rails

Example for my article about ES6 + Asset Pipeline
Ruby
14
star
73

whiteboard

A small app using Canvas + Socket.IO to provide a shared whiteboard.
JavaScript
14
star
74

sublime-better-rspec

Better RSpec syntax highlighting, with matchers for v3. Also includes implementation/spec toggling command.
Python
13
star
75

ar-sequence

Add support for PostgreSQL's SEQUENCE on ActiveRecord migrations.
Ruby
13
star
76

page_meta

Easily define <meta> and <link> tags. I18n support for descriptions, keywords and titles.
Ruby
13
star
77

boppers-uptime

A bopper to check if your sites are online.
Ruby
13
star
78

has_versions

A simple plugin to version ActiveRecord objects
Ruby
13
star
79

csr

Generate CSR (Certificate Signing Request) using Ruby and OpenSSL.
Ruby
13
star
80

haikunate

Generate Heroku-like memorable random names like adorable-ox-1234.
Ruby
13
star
81

module-component

Define auto-discoverable HTML UI components using Module.js.
JavaScript
12
star
82

alfred-workflows

Alfred workflows
12
star
83

twitter_cleanup

Remove old tweets periodically using Github Actions
Ruby
12
star
84

storage

This gem provides a simple API for multiple storage backends. Supported storages: Amazon S3 and FileSystem.
Ruby
12
star
85

has_layout

Add conditional layouts with ease
Ruby
11
star
86

kalendar

A view helper that creates a calendar using a table. You can easily add events with any content.
Ruby
11
star
87

stellar-paperwallet

Make paper wallets to keep your Stellar addresses safe.
JavaScript
10
star
88

tagger

Tagging plugin for Ruby on Rails apps
Ruby
10
star
89

page_title

Set the page title on Rails apps.
Ruby
10
star
90

dogo

A simple URL shortener service backed by Redis.
Ruby
10
star
91

has_notifications

This plugin was created to act as a proxy between different notification systems (Mail, Jabber, etc) based on the user's preferences.
Ruby
10
star
92

formatter

has_markup is an ActiveRecord plugin that integrates Tidy, Markdown, Textile and sanitize helper method into a single plugin.
Ruby
10
star
93

shortcuts

Because mouse is for noobies.
Ruby
9
star
94

ar-enum

Add support for creating `ENUM` types in PostgreSQL with ActiveRecord
Ruby
9
star
95

ar-timestamptz

Make ActiveRecord's PostgreSQL adapter use timestamptz as datetime columns.
Ruby
9
star
96

parsel-js

Encrypt and decrypt data with a given key.
JavaScript
8
star
97

access_token

Access token for client-side and API authentication.
Ruby
8
star
98

ember-and-rails

Ruby
8
star
99

sinatra-oauth-twitter

Sample app used on Guru-SP meetup
Ruby
8
star
100

bolt

A nicer test runner for golang
Go
8
star