Hung-Yi's LogoHung-Yi’s Journal

Browse URLs in Emacs under WSL

If you use GUI Emacs under WSL and you want your links to open in your browser on Windows, this post explains how to achieve that.

I use Emacs under WSL2 to take advantage of better performance compared to running it natively on Windows, but out of the box the browser integration doesn’t work well. By default Emacs will try to open the browser installed within WSL, and since most people won’t have one, Emacs will throw its hands in the air and give up.

Wouldn’t it be nice if Emacs could somehow forward “browse URL” requests through to Windows and have Windows decide the default browser to open it in?

Well, it can! Simply paste this snippet into your config.el and evaluate it or restart Emacs.

(when (and (eq system-type 'gnu/linux)
           (string-match
            "Linux.*Microsoft.*Linux"
            (shell-command-to-string "uname -a")))
  (setq
   browse-url-generic-program  "/mnt/c/Windows/System32/cmd.exe"
   browse-url-generic-args     '("/c" "start")
   browse-url-browser-function #'browse-url-generic))

Explanation

First we check if Emacs is running under Linux. If it’s running natively under Windows, do nothing since no forwarding is necessary.

Then to see if we’re specifically running under WSL, run string-match on the output of the shell command uname -a to see if it matches the regular expression1 Linux.*Microsoft.*Linux.

If we’re in a WSL environment, then set up some global parameters for the browse-url-generic function so that it “browses” using the Windows-specific command2 cmd.exe /c start {some-website}. This command actually opens the website in your default browser in Windows.

Try it out!

Type cmd.exe /c start "https://google.com/" into a Windows command prompt and watch Google open in your favorite browser.

Finally, we tell Emacs to use the browse-url-generic function to handle “browse URL” requests everywhere within Emacs.

Footnotes:

1

Emacs has its own idiosyncratic version of regular expressions. If you’re already familiar with the more normal variants of regexes, you may experience some pain. I certainly did.

2

I also tried using explorer.exe since it should be able to open URLs and it made more sense to me to let the Windows shell handle it. This worked for a while, but I found certain YouTube URLs would just fail to be forwarded correctly, and it wasn’t a problem with Emacs. Switching back to the widely recommended cmd.exe /c start approach has worked beautifully in all circumstances.