# 使用 Python 创建 Chrome 插件

> 原文： [https://pythonspot.com/create-a-chrome-plugin-with-python/](https://pythonspot.com/create-a-chrome-plugin-with-python/)

<caption id=”attachment_4920” align=”alignright” width=”300”]![chrome extension made with python](img/97cad8fbf9745375f3af2d417ebcad07.jpg)

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](https://developer.chrome.com/extensions/getstarted)

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](https://pythonspot.com/en/download-code/?id=L3dwLWNvbnRlbnQvdXBsb2Fkcy8yMDE2LzA4L2Nocm9tZS1leHRlbnNpb24tdHV0b3JpYWwuemlw)
_(and scroll down to Method B)_

## 创建一个 Google Chrome 插件

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

```py
{
  "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

```py
<!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](chrome://extensions) and press developer mode. Press “load unpacked extension”, select your directory and press ok.

## 将 Python 添加到 Chrome 扩展程序

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

*   方法 A：将 Brython 包含在 iframe 中（需要服务器）

*   方法 B：使用 Rapydscript（最佳，无服务器，纯扩展）将 Python 编译为 Javascript。

## 方法 A：iframe 中的 Python（Brython）

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:

```py
<!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.

<caption id=”attachment_483” align=”alignnone” width=”1000”]![Python inside Google Chrome](img/e4b79ccb91cef551723600488e9cb81b.jpg)

Python inside Google Chrome

## 运行您自己的脚本

要运行您自己的脚本，只需更改 popup.html 框架内的 url：

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

```

该脚本应在您自己的服务器上运行。 您可以从网络运行任何 Brython 脚本。 使用 Brython，您只需在 script 标签内键入 Python 代码。 看看[这个](view-source:http://brython.info/gallery/hello.html) Brython 示例，或者只是[浏览图库](http://brython.info/gallery/gallery_en.html?lang=en)。

## 方法 B：将 Python 编译为 Javascript。 （无服务器，纯扩展名）

There are several tools to compile Python to Javascript. [Rapydscript](http://www.rapydscript.com/) works fine, [Pyjs](http://pyjs.org/) does not work well with chrome (requires special parameter on start).
Install Rapydscript with:

```py

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

```

从此站点下载代码：

[下载扩展代码](https://pythonspot.com/en/download-code/?id=L3dwLWNvbnRlbnQvdXBsb2Fkcy8yMDE2LzA4L2Nocm9tZS1leHRlbnNpb24tdHV0b3JpYWwuemlw)
将文件/src/hello.py 更改为所需的文件：

```py

# 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')

```

跑：

```py

./make.sh

```

您可以在/ compiledpythonextension /中找到您的扩展名。 将其作为未打包的扩展程序加载到 chrome 中，并查看其工作情况:-)

## 结论：

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).

发表评论:-)