chrome的通讯:
- Background Page
- Popup Page
- Page Action and Browser Action
- Content Script
- Web Page Script
以下为mainfest.json文件
{ "name": "__MSG_extName__", "version": "1.0", "description": "__MSG_extDescription__", "default_locale": "zh_TW", "icons": { "16": "images/icon_16.png", "32": "images/icon_32.png", "64": "images/icon_64.png", "128": "images/icon_128.png" }, "background_page": "background.html", "popup": "popup.html", "options_page": "options.html", "permissions": [ "tabs", "http://www.google.com/ig/*", "http://img0.gmodules.com/ig/images/weather/", "geolocation" ], "browser_action": { "default_icon": "images/loading.png", "default_title": "__MSG_extName__", "default_popup": "popup.html" } }这里面需要解释的是
popup、options_page和background_page
这三个项:
- popup放置的是popup.html(也就是前置页面)
- background_page放置的是background.html(也就是后台页面)
- option_page放置的是option_page.html(也就是选项页面)
这三个页面均不规定文件名
permissions要求输入的是允许项目:上面写的有
- tabs(允许选项页交互)
- http://www.google.com/ig/*(允许访问该网站)
- http://img0.gmodules.com/ig/images/weather/(同上)
- geolocation(允许使用定位功能)
详细的API大家可以查阅
这里面用一个天气预报extension来做说明
文件夹说明:_locales文件夹包含当地字符json文件,分别为zh_TW和en,images文件夹包含各个大小的icon文件,icon路径信息已经在mainfest.json写出。
background.html
<html> <head> <meta charset="utf-8" /> <script type="text/javascript" src="jquery.min.js"></script> <script> var errorCode; var lat; var lng; var weatherXML; var current; var locale=chrome.i18n.getMessage("locale"); function getCurrentLocation() { console.log("getCurrentLocation()"); navigator.geolocation.getCurrentPosition(success, error); } function success(position) { console.log(position); lat=Math.round(position.coords.latitude*1000000); lng=Math.round(position.coords.longitude*1000000); getWeather(); } function error(msg) { console.log(msg); chrome.browserAction.setBadgeText({text:"?"}); errorCode="unable_to_locate_your_position"; } function getWeather() { console.log("http://www.google.com/ig/api?hl="+locale+"&weather=,,,"+lat+","+lng); $.get("http://www.google.com/ig/api?hl="+locale+"&weather=,,,"+lat+","+lng, function(data) { weatherXML=data; if($(weatherXML).find("weather current_conditions").length==1) { errorCode=""; current={}; current.condition=$(weatherXML).find("current_conditions condition").attr("data"); current.temp_c=$(weatherXML).find("current_conditions temp_c").attr("data")+"℃"; current.temp_f=$(weatherXML).find("current_conditions temp_f").attr("data")+"℉"; current.humidity=$(weatherXML).find("current_conditions humidity").attr("data"); current.wind_condition=$(weatherXML).find("current_conditions wind_condition").attr("data"); current.icon="http://img0.gmodules.com"+$(weatherXML).find("current_conditions icon").attr("data"); console.log(current); var temp_mode=localStorage["temperature_mode"]; if(!temp_mode) { temp_mode="C"; } switch(temp_mode){ case "C": chrome.browserAction.setBadgeText({text:current.temp_c}); break; case "F": chrome.browserAction.setBadgeText({text:current.temp_f}); break; } chrome.browserAction.setIcon({path:current.icon}); } else { chrome.browserAction.setBadgeText({text:"?"}); errorCode="unable_to_load_data"; } }); } function startRequest() { getCurrentLocation(); } function scheduleRequest() { var reqeustInterval = 1000 * 60 * 5; console.log("Scheduling request..."); window.setTimeout(startRequest, reqeustInterval); } startRequest(); scheduleRequest(); </script> </head> </html>
option.html
<html> <head> <meta charset="utf-8" /> <link type="text/css" rel="stylesheet" href="style.css" /> <script type="text/javascript" src="jquery.min.js"></script> <script> function saveOption() { if(localStorage["temperature_mode"] != $('input[name=temp_mode]:checked').val()) { localStorage["temperature_mode"] = $('input[name=temp_mode]:checked').val(); chrome.extension.getBackgroundPage().getWeather(); } console.log(localStorage["temperature_mode"]); $("#status").html(chrome.i18n.getMessage("option_saved")+"<a href='javascript:window.close();'>"+chrome.i18n.getMessage("click_here_to_close")+"</a>"); } function restoreOption() { var temp_mode=localStorage["temperature_mode"]; if(!temp_mode) { return; }else { switch(temp_mode) { case "C": $("input[name=temp_mode]")[0].checked=true; break; case "F": $("input[name=temp_mode]")[1].checked=true; break; default: console.log("error"); } } } function renderPage() { $("#temperature_scale").html(chrome.i18n.getMessage("temperature_scale")); $("#celsius").html(chrome.i18n.getMessage("celsius")); $("#fahrenheit").html(chrome.i18n.getMessage("fahrenheit")); $("#save").html(chrome.i18n.getMessage("save")); } </script> </head> <body onload="restoreOption();renderPage();"> <span id="temperature_scale"></span><input type="radio" name="temp_mode" value="C" checked><span id="celsius"></span> <input type="radio" name="temp_mode" value="F"><span id="fahrenheit"></span><br> <button onclick="saveOption();"><span id="save"></span></button> <div id="status"></div> </body> </html>
Message.json文件,即中文字库
{ "extName": { "message": "現在天氣怎麼樣", "description":"擴充套件名稱" }, "extDescription": { "message": "顯示所在地現在的天氣狀態", "description":"擴充套件描述" }, "locale": { "message": "zh-tw", "description":"要傳送給Google Weather API的語系編碼" }, "loading": { "message": "資料載入中...", "description":"載入資料時的popup內容" }, "unable_to_load_data": { "message": "無法載入資料。", "description":"資料載入錯誤時的popup內容" }, "unable_to_locate_your_position": { "message": "無法確定目前所在位置。", "description":"無法定位時的popup內容" }, "temperature_unit": { "message": "溫度單位", "description":"用於options.html" }, "celsius":{ "message": "攝氏", "description":"溫度單位,用於options.html" }, "fahrenheit":{ "message": "華氏", "description":"溫度單位,用於options.html" }, "save":{ "message": "儲存", "description":"儲存設定" }, "option_saved":{ "message": "儲存完成。", "description":"儲存完成" }, "click_here_to_close":{ "message": "按此關閉", "description":"按此關閉" } }
这里用到了几个chrome的交互函数
chrome.i18n.getMessage() 可以参考http://code.google.com/chrome/extensions/i18n.html
Gets the localized string for the specified message. If the message is missing, this method returns an empty string (''). If the format of the
getMessage()
call is wrong — for example, messageName is not a string or the substitutions array is empty or has more than 9 elements — this method returnsundefined
.
chrome.browserAction.setBadgeText() 可以参考http://code.google.com/chrome/extensions/browserAction.html
Sets the badge text for the browser action. The badge is displayed on top of the icon.
chrome.browserAction.setIcon() 可以参考http://code.google.com/chrome/extensions/browserAction.html
Sets the icon for the browser action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element. Either the path or the imageData property must be specified.
chrome.extension.getBackgroundPage() 可以参考http://code.google.com/chrome/extensions/extension.html
Returns the JavaScript 'window' object for the background page running inside the current extension. Returns null if the extension has no background page.
完整代码: