本文由 伯樂在線 - xianhu 翻譯,Daetalus 校稿。未經許可,禁止轉載!
英文出處:pythonspot.com。歡迎加入翻譯小組。
谷歌Chrome插件是使用HTML、JavaScript和CSS編寫的。如果你之前從來沒有寫過Chrome插件,我建議你讀一下這個。在這篇教程中,我們將教你如何使用Python代替JavaScript。
創建一個谷歌Chrome插件
首先,我們必須創建一個清單文件:manifest.json。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
{
"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/"
]
}
|
然后創建一個名為popup.html的文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
<!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
>
|
最后得到一個圖標,並保存為icon.png。打開chrome://extensions,點擊開發者模式。點擊“加載未打包擴展程序”,選擇文件夾,點擊OK。
為Chrome擴展程序添加Python
現在你擁有了最基本的權利,我們可以在代碼中添加Python。為了能在一個瀏覽器中運行Python,你有很多個選擇,包括Brython和emcascripten。我們決定使用Brython。我們將從一個服務器運行Brython腳本。改變popup.html的內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<!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
>
|
重啟下你的插件,你就會在你的谷歌Chrome瀏覽器中得到一個Python(Brython)解釋器。
運行你自己的腳本
為了能夠運行你自己的腳本,簡單地修改一下popup.html框架中的url即可:
1
|
<
iframe
src
=
"BRYTHON SCRIPT URL"
id
=
"frame"
seamless
=
"seamless"
scrolling
=
"no"
></
iframe
>
|
這個腳本應該運行在你自己的服務器上。你可以從網上運行任意的Brython腳本。利用Brython,你可以簡單地在腳本標簽中輸入Python代碼。看一下這個Brython的例子,或者簡單地瀏覽下這個網站。
總結:
Chrome插件是使用HTML、JavaScript和CSS創建的。我們想知道在谷歌Chrome插件中能否使用Python代碼。我們最終得到了一個瀏覽器中的Python解釋器和執行Python腳本的能力。記住,這只是個實現性的結果,只是一個玩具,在這一點上,我不建議你將所有的插件都移植或建立在Brython上。