Create a chrome plugin with Python

chrome extension made with python
Google Chrome extension created with Python (serverless, method B). (click to zoom)
Google Chrome plugins are written in HTML, JavaScript and and CSS. If you have never written a Chrome plugin before I suggest chrome extensions documentation

You can use Python instead of JavaScript and in this tutorial we will show you how to do that.

In a hurry? Download the code from this site:
Download Extension Code
(and scroll down to Method B)

Create an Google Chrome Plugin

To start, we will have to create a manifest file: manifest.json.

{
  "manifest_version": 2,
 
  "name": "Python Chrome Plugin",
  "description": "This extension runs Python code.",
  "version": "1.0",
 
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/"
  ]
}

Create a file called popup.html

<!doctype html>
<!--
 This page is shown when the extension button is clicked, because the
 "browser_action" field in manifest.json contains the "default_popup" key with
 value "popup.html".
 -->
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
      body {
        font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
        font-size: 100%;
      }
      #status {
        /* avoid an excessively wide status text */
        white-space: pre;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 400px;
      }
    </style>
 
    <!--
      - JavaScript and HTML must be in separate files: see our Content Security
      - Policy documentation[1] for details and explanation.
      -
      - [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
     -->
    <script src="popup.js"></script>
  </head>
  <body>
    <div id="status"></div>
    <img id="image-result" hidden>
  </body>
</html>

Finally get an icon and save it as icon.png. Open chrome://extensions and press developer mode. Press “load unpacked extension”, select your directory and press ok.

Adding Python to the Chrome extension

We have two options to add Python into a chrome extension:

  • Method A: Include Brython in an iframe (requires server)
  • Method B: Compile Python to Javascript using Rapydscript (best, serverless, pure extension.)

Method A: Python (Brython) in iframe

Now that you have the basics right we can add Python to the code. To run Python in the browser you have several options including Brython and emcascripten. We decided to give Brython a try. We will run the Brython script from a server. Change popup.html to:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta charset="iso-8859-1">
<style>
body {    
    margin: 0 !important;
    padding: 0 !important;
    width: 800;
}
 
#frame {
    overflow: hidden;
    width:790;
    height:324;
}
</style>
</head>
<body onLoad="">
<iframe src=http://brython.info/console.html id="frame" seamless="seamless" scrolling="no"></iframe>
</body>
</html>

Once you restart your plugin you will have a Python (Brython) interpreter inside your Google Chrome.

Python inside Google Chrome
Python inside Google Chrome

Running your own scripts
To run your own script simply change the url inside the popup.html frame:

<iframe src="BRYTHON SCRIPT URL" id="frame" seamless="seamless" scrolling="no"></iframe>

The script should run on your own server. You can run any Brython script from the web. Using Brython you can simply type Python code inside the script tags. Have a look at this Brython examples or simply browse the gallery.

Method B: Compile Python to Javascript. (no server, pure extension)

There are several tools to compile Python to Javascript. Rapydscript works fine, Pyjs does not work well with chrome (requires special parameter on start).
Install Rapydscript with:

sudo apt-get install npm
sudo ln -s /usr/bin/nodejs /usr/bin/node
sudo npm install rapydscript

Download the code from this site:
Download Extension Code
Change the file /src/hello.py to you needs:

# Example Python script 
# (for rapydscript, a python to javascript compiler)
 
#def doHelloMessage():
#    alert('hello')
#doHelloMessage()
 
# modify html page
document.getElementById("result").innerHTML = 'Compiled Python script in Chrome' 
 
# write into log 
console.log('hello from python')

Run:

./make.sh

You can find your extension in /compiledpythonextension/. Load it in chrome as unpackaged extension and see it working 🙂

Concluding:

Chrome plugins are created using HTML, JavaScript and CSS. We can use Python to create normal Chrome extensions using a Python to Javascript compiler (Rapydscript).

Leave a comment 🙂
 

Fun tricks with Python

You may like:
Teach Your Kids to Code: Learn Python Programming at Any Age

Starting a simple HTTP web server
A simple HTTP Server can be started in seconds.

python -m SimpleHTTPServer

For Python3:

python -m http.server

Once started you can open http://127.0.0.1:8000/. The browser will show you the contents of the directory.

A funny text
Try the statement below to display a poem by Tim Peters.

import this

XKCD web comic
You can open a comic on XKCD using:

import antigravity

Using Zip to combine arrays
You can zip the two arrays with:

b = [[1, 2, 3, 4], [6, 5, 4, 3]]
zip(*b)
[(1, 6), (2, 5), (3, 4), (4, 3)]

Reverse a list
To reverse a list, you could implement a function. But why go through the trouble if it’s already implemented?

b = [1,2,3,4,5]
b.reverse()
print b
[5, 4, 3, 2, 1]

Reverse a string
Instead of creating a method to reverse a string you can use:

s = "Hello world"
s = s[::-1]
print s
dlrow olleH

Swapping variables
You do not need to define a temporary variable to swap to variables in Python:

a = 1
b = 3
b,a = a,b
print a
print b
1

If you know of any tips or tricks, leave a comment. 🙂