Home » Ruby » Open the default browser in Ruby

Open the default browser in Ruby

Posted by: admin November 30, 2017 Leave a comment

Questions:

In Python, you can do this:

import webbrowser
webbrowser.open_new("http://example.com/")

It will open the passed in url in the default browser

Is there a ruby equivalent?

Answers:

Cross-platform solution

First, install the Launchy gem:

$ gem install launchy

Then, you can run this:

require 'launchy'

Launchy.open("http://stackoverflow.com")

Questions:
Answers:

Mac-only solution:

system("open", "http://stackoverflow.com/")

or

`open http://stackoverflow.com/`

Questions:
Answers:

This should work on most platforms:

link = "Insert desired link location here"
if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
  system "start #{link}"
elsif RbConfig::CONFIG['host_os'] =~ /darwin/
  system "open #{link}"
elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/
  system "xdg-open #{link}"
end

Questions:
Answers:

Simplest Win solution:

`start http://www.example.com`

Questions:
Answers:

Linux-only solution

system("xdg-open", "http://stackoverflow.com/")

Questions:
Answers:

This also works:

system("start #{link}")

Questions:
Answers:

Windows Only Solution:

require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute(...)

Shell Execute on MSDN

Questions:
Answers:

If it’s windows and it’s IE, try this: http://rubyonwindows.blogspot.com/search/label/watir also check out Selenium ruby: http://selenium.rubyforge.org/getting-started.html

HTH