動(dòng)手寫(xiě)一款簡(jiǎn)單的chrome天氣插件

極簡(jiǎn)天氣

一款簡(jiǎn)單的chrome天氣插件。

github https://github.com/yohnz/weather
如圖:

1.png

創(chuàng)建文件

新建weather文件夾,里面包含manifest.json,popup.html和images文件夾。images文件夾放16,48,128三種不同尺寸的圖標(biāo)

manifest.json內(nèi)代碼如下:

{
  "manifest_version":2,
  "name":"極簡(jiǎn)天氣",
  "description":"極簡(jiǎn)天氣預(yù)報(bào)",
  "version":"1.0",
  "icons": {
        "16": "images/sun16.png",
        "48": "images/sun48.png",
        "128": "images/sun128.png"
   },
  "browser_action":{
      "default_icon":"images/sun48.png",
      "default_title":"天氣預(yù)報(bào)",
      "default_popup":"popup.html"
  },
   
}

popup.html的代碼如下:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>天氣</title>
</head>
<body>
 <div class="weather">    
    Test    
 </div>
</body>
</html>

文件說(shuō)明

manifest.json

必需文件,是整個(gè)擴(kuò)展的入口,每個(gè)Chrome擴(kuò)展都包含一個(gè)Manifest文件。Manifest必須包含name、version和manifest_version屬性。

屬性說(shuō)明:

  • manifest_version指定文件格式的版本,在Chrome18之后,應(yīng)該都是2
  • name擴(kuò)展名稱
  • version 擴(kuò)展版本號(hào)
  • version擴(kuò)展的版本
  • icons擴(kuò)展列表圖標(biāo)
  • browser_action指定擴(kuò)展在Chrome工具欄中的顯示信息。
  • default_icondefault_titledefault_popup依次指定圖標(biāo)、標(biāo)題、對(duì)應(yīng)的頁(yè)面

Popup頁(yè)面

Popup頁(yè)面是當(dāng)用戶點(diǎn)擊擴(kuò)展圖標(biāo)時(shí),展示在圖標(biāo)下面的頁(yè)面。

打開(kāi)chrome擴(kuò)展程序界面,勾選"開(kāi)發(fā)者模式",拖入weather文件夾,然后就可以看到weather擴(kuò)展已經(jīng)出現(xiàn)在chrome擴(kuò)展程序列表了

1.jpg

同時(shí),工具欄也出現(xiàn)了weather的圖標(biāo),點(diǎn)擊之后會(huì)彈出popup界面:

2.jpg

完善頁(yè)面和樣式

完善靜態(tài)popup頁(yè)面,模擬天氣數(shù)據(jù):

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>天氣</title>
</head>
<body>
    <div class="weather">
        <div class="today" id="today">
            <h1 class="city">廈門</h1>
            <div class="row_detail">![](http://upload-images.jianshu.io/upload_images/1281368-9e0ad1352ce6bb91.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
                <h1>19<span>℃</span></h1></div>
            <div class="wind">
                <h2>陰</h2>
                <h4>風(fēng)速 20   濕度 89%</h4></div>
        </div>
        <div class="content">
            <div class="wrap" id="wrap">
                <div class="row">
                    <h4>2016-05-16</h4>![](http://upload-images.jianshu.io/upload_images/1281368-9e0ad1352ce6bb91.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
                    <h1>19~24</h1>
                    <h4>陰</h4>
                </div>               
            </div>
        </div>
    </div>
</body>
</html>

新建CSS文件,并在popup頁(yè)面引入

body{
    width:740px;
    height:400px;
    font-family: 'Microsoft Yahei';
    color:#333;
    background:#fefefe;
    text-shadow:1px 1px 6px #333;
}

.city{
    text-align:center
}
.today{
    padding-bottom:30px;
}
.row_detail{
    display: flex;
    direction: row;
    justify-content:center;
    align-items: center;
}
.row_detail img{
    width:80px;    
}
.row_detail h1{
    font-size:60px;
}
.wind{
    text-align: center;
}
.content{
    display: flex;
    direction: column
}

.wrap{
    display: flex;
    direction: row;
    flex: 1;
    justify-content:space-around;
    align-items: center;
}
.row{
    background:#fff;
    border:1px solid #ccc;
    padding:10px;
    box-shadow: 0 2px 10px rgba(0,0,0,.3);
}
.row img{
    width:80px;
}
.row h1{
    font-size:18px;
}
h1,h4{
    text-align: center;
    margin:0;
}

點(diǎn)擊工具欄weather圖標(biāo),此時(shí)界面如圖:

3.jpg

獲取真實(shí)天氣數(shù)據(jù)

Google允許Chrome擴(kuò)展應(yīng)用不必受限于跨域限制。但出于安全考慮,需要在Manifest的permissions屬性中聲明需要跨域的權(quán)限。
這里以和風(fēng)天氣API為例.
首先,在Manifest里添加要請(qǐng)求的API接口:

"permissions":[
     "http://api.openweathermap.org/data/2.5/forecast?q=*",   
  ]

然后新建popup.js并在popup頁(yè)面中引入
簡(jiǎn)單的ajax函數(shù):

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();
}

和風(fēng)天氣API可以通過(guò)城市名稱,城市代碼,IP三種方式來(lái)獲取指定城市天氣數(shù)據(jù),不過(guò)經(jīng)過(guò)測(cè)試發(fā)現(xiàn),IP獲取的方式不準(zhǔn)確,城市有偏差,所以,直接用城市名稱來(lái)獲取。這里借用http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json獲取城市名稱。

httpRequest('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json',function(data) {
    if(!data) return;
    data = JSON.parse(data);
    var city = data.city;
    var url = 'https://api.heweather.com/x3/weather?city='+city+'&key=youkey';
        httpRequest(url,function(data) {
            data = JSON.parse(data);
            var result = data["HeWeather data service 3.0"][0];        
            showWeather(city,result);            
        });
});

為了方便的解析圖片,構(gòu)建一個(gè)json

var cond_info = {
100:"http://files.heweather.com/cond_icon/100.png",
101:"http://files.heweather.com/cond_icon/101.png",
102:"http://files.heweather.com/cond_icon/102.png",
103:"http://files.heweather.com/cond_icon/103.png",
104:"http://files.heweather.com/cond_icon/104.png",
200:"http://files.heweather.com/cond_icon/200.png",
201:"http://files.heweather.com/cond_icon/201.png",
202:"http://files.heweather.com/cond_icon/202.png",
203:"http://files.heweather.com/cond_icon/203.png",
204:"http://files.heweather.com/cond_icon/204.png",
205:"http://files.heweather.com/cond_icon/205.png",
206:"http://files.heweather.com/cond_icon/206.png",
207:"http://files.heweather.com/cond_icon/207.png",
208:"http://files.heweather.com/cond_icon/208.png",
209:"http://files.heweather.com/cond_icon/209.png",
210:"http://files.heweather.com/cond_icon/210.png",
211:"http://files.heweather.com/cond_icon/211.png",
212:"http://files.heweather.com/cond_icon/212.png",
213:"http://files.heweather.com/cond_icon/213.png",
300:"http://files.heweather.com/cond_icon/300.png",
301:"http://files.heweather.com/cond_icon/301.png",
302:"http://files.heweather.com/cond_icon/302.png",
303:"http://files.heweather.com/cond_icon/303.png",
304:"http://files.heweather.com/cond_icon/304.png",
305:"http://files.heweather.com/cond_icon/305.png",
306:"http://files.heweather.com/cond_icon/306.png",
307:"http://files.heweather.com/cond_icon/307.png",
308:"http://files.heweather.com/cond_icon/308.png",
309:"http://files.heweather.com/cond_icon/309.png",
310:"http://files.heweather.com/cond_icon/310.png",
311:"http://files.heweather.com/cond_icon/311.png",
312:"http://files.heweather.com/cond_icon/312.png",
313:"http://files.heweather.com/cond_icon/313.png",
400:"http://files.heweather.com/cond_icon/400.png",
401:"http://files.heweather.com/cond_icon/401.png",
402:"http://files.heweather.com/cond_icon/402.png",
403:"http://files.heweather.com/cond_icon/403.png",
404:"http://files.heweather.com/cond_icon/404.png",
405:"http://files.heweather.com/cond_icon/405.png",
406:"http://files.heweather.com/cond_icon/406.png",
407:"http://files.heweather.com/cond_icon/407.png",
500:"http://files.heweather.com/cond_icon/500.png",
501:"http://files.heweather.com/cond_icon/501.png",
502:"http://files.heweather.com/cond_icon/502.png",
503:"http://files.heweather.com/cond_icon/503.png",
504:"http://files.heweather.com/cond_icon/504.png",
506:"http://files.heweather.com/cond_icon/506.png",
507:"http://files.heweather.com/cond_icon/507.png",
508:"http://files.heweather.com/cond_icon/508.png",
900:"http://files.heweather.com/cond_icon/900.png",
901:"http://files.heweather.com/cond_icon/901.png",
999:"http://files.heweather.com/cond_icon/999.png"
}

showWeather()函數(shù)構(gòu)建DOM;

function showWeather(city,result) { 
    var daily = result.daily_forecast;
    var now = result.now;
    var dailyDom='';
    for(var i=0;i<daily.length;i++){
        var day = daily[i];
         dailyDom += '<div class="row">'
            +'<h4>'+day.date+'</h4>'
            +'[站外圖片上傳中……(3)]'
            +'<h1>'+day.tmp.min+'~'+day.tmp.max+'</h1>'
            +'<h4>'+day.cond.txt_d+'</h4>'     
        +'</div>'       
    }
    var today = '<h1 class="city">'+city+'</h1>'
                +'<div class="row_detail">'
                    +'[站外圖片上傳中……(4)]'
                    +'<h1>'+now.tmp+'<span>℃</span></h1>'            
                +'</div>'
                +'<div class="wind">'
                    +'<h2>'+now.cond.txt+'</h2>'
                    +'<h4>風(fēng)速 '+now.wind.spd+'   濕度 '+now.hum+'%</h4>'            
                +'</div>'
    
    document.getElementById('today').innerHTML = today;
    document.getElementById('wrap').innerHTML = dailyDom; 
}

這時(shí),再點(diǎn)擊weather圖標(biāo),天氣擴(kuò)展基本上就完成了,不過(guò)因?yàn)楹惋L(fēng)API有請(qǐng)求次數(shù)限制,也為了減少請(qǐng)求,這里做一下數(shù)據(jù)緩存。

var _time = new Date().getTime()-(60*60*1000*2); //接口次數(shù)有限,兩小時(shí)請(qǐng)求一次
var storageTime = localStorage.updateTime||0;

httpRequest('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json',function(data) {
    if(!data) return;
    data = JSON.parse(data);
    var city = data.city;
    var url = 'https://api.heweather.com/x3/weather?city='+city+'&key=youkey';
    if(_time>storageTime){
        httpRequest(url,function(data) {
            data = JSON.parse(data);
            var result = data["HeWeather data service 3.0"][0];        
            showWeather(city,result);
            localStorage.updateTime = new Date().getTime();  
            localStorage.data = JSON.stringify(result);    
        });
    }else{
        var result = JSON.parse(localStorage.data);
        showWeather(city,result);
    }

});

至此,一個(gè)簡(jiǎn)單的chrome天氣擴(kuò)展就完成了,是不是比想象中更簡(jiǎn)單?如果覺(jué)得本文有幫助,請(qǐng)github賞個(gè)star~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容