來源:http://developer.chrome.com/extensions/
1,Getting Started
a,你可以基於任何Chrome的發行版開發extension
b,概念:Browser Action,extension和Chrome之間的橋梁,可以幫你在Chrome的工具欄添加一個按鈕,由你來控制按鈕的行為。
創建方式:首先,在你的PC上建立一個文件夾;其次,在該文件夾里創建一個manifest.json,然后按照教程上添加以下代碼:
{ "name": "My First Extension", "version": "1.0", "manifest_version": 2, "description": "The first extension that I made.", "browser_action": { "default_icon": "icon.png" }, "permissions": [ "http://api.flickr.com/" ] }
最后,添加一個png格式的按鈕圖標就可以了。
加載extension的方法:工具-->擴展程序 --> 載入正在開發的擴展程序,找到那個文件夾然后加載就行了,manifest.json會被自動解析,圖標被加到工具欄里了。如果沒有任何其它代碼,按下那個按鈕當然沒啥反應了。
c,向extension中添加代碼
第一步,編輯manifest.json添加新的一行,指出彈出頁面的html描述
... "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, ..
第二步,在剛才創建extension文件的文件夾里,創建兩個文件popup.html和popup.js,然后添加code:
<!doctype html> <html> <head> <title>Getting Started Extension's Popup</title> <style> body { min-width:357px; overflow-x:hidden; } img { margin:5px; border:2px solid black; vertical-align:middle; width:75px; height:75px; } </style> <!-- JavaScript and HTML must be in separate files for security. --> <script src="popup.js"></script> </head> <body> </body> </html>
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var req = new XMLHttpRequest(); req.open( "GET", "http://api.flickr.com/services/rest/?" + "method=flickr.photos.search&" + "api_key=90485e931f687a9b9c2a66bf58a3861a&" + "text=hello%20world&" + "safe_search=1&" + // 1 is "safe" "content_type=1&" + // 1 is "photos only" "sort=relevance&" + // another good one is "interestingness-desc" "per_page=20", true); req.onload = showPhotos; req.send(null); function showPhotos() { var photos = req.responseXML.getElementsByTagName("photo"); for (var i = 0, photo; photo = photos[i]; i++) { var img = document.createElement("image"); img.src = constructImageURL(photo); document.body.appendChild(img); } } // See: http://www.flickr.com/services/api/misc.urls.html function constructImageURL(photo) { return "http://farm" + photo.getAttribute("farm") + ".static.flickr.com/" + photo.getAttribute("server") + "/" + photo.getAttribute("id") + "_" + photo.getAttribute("secret") + "_s.jpg"; }
第三步,在extension的頁面重新加載一下就行了。
回顧一下,相比於做HTML5的web程序來講,extension只是多了一個配置文件manifest.json。其次就是JS里面可以用一些針對extension訂制的API。