Chrome扩展开发学习笔记之带选项页面的扩展

简介

有一些扩展允许用户进行个性化设置,这样就需要向用户提供一个选项页面。Chrome通过Manifest文件的options_page属性为开发者提供了这样的接口,可以为扩展指定一个选项页面。当用户在扩展图标上点击右键,选择菜单中的“选项”后,就会打开这个页面。对于没有图标的扩展,可以在chrome://extensions页面中单击“选项”。

对于网站来说,用户的设置通常保存在Cookies中,或者保存在网站服务器的数据库中。对于JavaScript来说,一些数据可以保存在变量中,但如果用户重新启动浏览器,这些数据就会消失。那么如何在扩展中保存用户的设置呢?我们可以使用HTML5新增的localStorage接口。localStorage是HTML5新增的方法,它允许JavaScript在用户计算机硬盘上永久储存数据(除非用户主动删除)。但localStorage也有一些限制,首先是localStorageCookies类似,都有域的限制,运行在不同域的JavaScript无法调用其他域localStorage的数据;其次是单个域在localStorage中存储数据的大小通常有限制(虽然W3C没有给出限制),对于Chrome这个限制是5MB ;最后localStorage只能储存字符串型的数据,无法保存数组和对象,但可以通过jointoStringJSON.stringify等方法先转换成字符串再储存。

天气预报扩展

我们将编写一个天气预报的扩展,这个扩展将提供一个选项页面供用户填写所关注的城市。有很多网站提供天气预报的API,我就用书上的地址:http://openweathermap.org/API

manifest文件

{
    "manifest_version": 2,
    "name": "天气预报",
    "version": "1.0",
    "description": "查看未来一周的天气情况",
    "icons": {
        "16": "images/icon16.png",
        "48": "images/icon48.png",
        "128": "images/icon128.png"
    },
    "browser_action": {
    "default_icon": {
        "19": "images/icon19.png",
        "38": "images/icon38.png"
    },
    "default_title": "天气预报",
    "default_popup": "popup.html"
    },
    "options_page": "options.html",
    "permissions": [
        "http://api.openweathermap.org/data/2.5/forecast/daily?q=*"
    ]
}

上面是这个扩展的Manifest文件,options.html为设定选项的页面。下面开始编写options.html文件。

options.html

<html>
<head>
<meta charset="UTF-8">
<title>设定城市</title>
</head>
<body>
<input type="text" id="city" />
<input type="button" id="save" value="保存" />
<script src="js/options.js"></script>
</body>
</html>

这个页面提供了一个id为city的文本框和一个id为save的按钮。由于Chrome不允许将JavaScript内嵌在HTML文件中,所以我们单独编写一个options.js脚本文件,并在HTML文件中引用它。下面来编写options.js文件。

options.js

var city = localStorage.city || 'beijing';
document.getElementById('city').value = city;
document.getElementById('save').onclick = function(){
localStorage.city = document.getElementById('city').value;
alert('保存成功。');
}

options.js的代码中可以看到,localStorage的读取和写入方法很简单,和JavaScript中的变量读写方法类似。

显示天气预报的结果,我们为扩展指定了一个popup.html页面。下面来编写这个UI页面。

popup.html

<html>
<head>
<meta charset="UTF-8">
<style>
    * {
        margin: 0;
        padding: 0;
    }
    body {
        width: 520px;
        height: 270px;
    }
    table {
        font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
        font-size: 12px;
        width: 480px;
        text-align: left;
        border-collapse: collapse;
        border: 1px solid #69c;
        margin: 20px;
        cursor: default;
    }
    table th {
        font-weight: normal;
        font-size: 14px;
        color: #039;
        border-bottom: 1px dashed #69c;
        padding: 12px 17px;
        white-space: nowrap;
    }
    table td {
        color: #669;
        padding: 7px 17px;
        white-space: nowrap;
    }
    table tbody tr:hover td {
        color: #339;
        background: #d0dafd;
    }
</style>
</head>
<body>
<div id="weather"></div>
<script src="js/weather.js"></script>
</body>
</html>

其中id为weather的div元素将用于显示天气预报的结果。下面来编写weather.js文件。

weather.js

function httpRequest(url,callback){
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            callback(xhr.responseText);
        }
    }
    xhr.send();
}
function showWeather(result){
    result = JSON.parse(result);
    var list = result.list;
    var city = localStorage.city;
    city = city?city:'beijing';
    var table = '<p>当前城市:'+city+'</p><table><tr><th>日期</th><th>天气</th><th>最低温度</th><th>最高温度</th></tr>';
    for(var i in list){
    var d = new Date(list[i].dt*1000);
    table += '<tr>';
    table += '<td>'+d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate()+'</td>';
    table += '<td>'+list[i].weather[0].description+'</td>';
    table += '<td>'+Math.round(list[i].temp.min-273.15)+' °C</td>';
    table += '<td>'+Math.round(list[i].temp.max-273.15)+' °C</td>';
    table += '</tr>';
    }
    table += '</table>';
    document.getElementById('weather').innerHTML = table;
}
var city = localStorage.city;
city = city?city:'beijing';
var url = 'http://api.openweathermap.org/data/2.5/forecast/daily?q='+city+',china&lang=zh_cn&&APPID=13000c581791f87070bf681c6e5df18e';
httpRequest(url, showWeather);
  • 设置城市

设置城市

  • weather扩展的运行界面

运行界面

小结

无论是options.js还是weather.js中都有如下语句:

var city = localStorage.city;
city = city?city:'beijing';

也就是说,当选项没有值时,应设定一个默认值,以避免程序出错。此处如果用户未设置城市,扩展将显示北京的天气预报。

页面中文乱码需要在head中加入<meta charset="UTF-8">

代码weather.js中请求的api地址中的APPID可以更改为大家自己注册账号生成的key。

OK,今天的学习就到这里了。本示例扩展的源代码可以通过 https://github.com/lanceWan/chrome-plugin/tree/master/Note03 下载得到。

本文同步地址:http://www.iwanli.me

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值