Home > firefox, python > [Python] Open a URL in Firefox in the *current* tab

[Python] Open a URL in Firefox in the *current* tab

Python is f*ing awesome. I realize it every single day. Here is the issue that I faced today:

Problem
From a Python script, I wanted to open a URL in the current tab of Firefox. How to do that?

Difficulty
In the standard library there is a module called webbrowser. However, it only has these functions: open, open_new, and open_new_tab, i.e. you can open a URL in a new window or in a new tab but not in the current tab!

Solution
After doing some research, I found a Firefox add-on (MozRepl) that allows you to program Firefox and other Mozilla-based applications from the inside. Here are some links:

Install the add-on, then go to Tools -> MozRepl -> Start. Here check the option “Activate on startup” too. Now fire up a terminal and try these commands:

$ telnet localhost 4242
Trying 127.0.0.1...
Connected to localhost.
...
repl> content.location.href = 'http://www.python.org'
repl> repl.quit()
Connection closed by foreign host.
$

Check the browser. You have http://www.python.org opened in your current tab. Great! But how to automate these steps from a script? How to automate a telnet session?

Automating telnet
Needless to say, there is a telnet module in the standard library :) Using it, I came up with the following solution:

#!/usr/bin/env python

# firefox.py

import telnetlib

HOST = 'localhost'
PORT = 4242

def open_curr_tab(url):
    tn = telnetlib.Telnet(HOST, PORT)
    cmd = "content.location.href = '{url}'".format(url=url)

    tn.read_until("repl> ")
    tn.write(cmd + "\n")

    tn.write("repl.quit()\n")

#############################################

if __name__ == "__main__":
    open_curr_tab('http://www.python.org')

If you put it in a module called firefox, then you can call it like this: firefox.open_curr_tab(url). Pretty awesome, I think.

Related
For closing the current tab, use gBrowser.removeCurrentTab() .

Links
I also looked at these links but I didn’t use them at the end:

Update (20121211)
I’ve made a Python module out of it. Available here as part of my jabbapylib library. Currently implemented methods:

  • open_curr_tab(url) : open URL in current tab
  • open_new_empty_tab() : open a new empty tab and put the focus on it
  • close_curr_tab() :close the current tab
  • is_mozrepl_installed() : test if MozRepl is installed
Advertisements
  1. fulibacsi
    December 11, 2012 at 13:50

    Nice! :)

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: