接下来,我们综合上面的配置,再加一个选项页面配置,做一个天气预报的小栗子。
栗子:天气预报:
主要是使用options_page
参数,增加配置页面。
{
"manifest_version":2,
"name":"天气预报",
"version":"1.0",
"description":"获取天气预报,同时可以配置不同地区的获取",
"icons":{
"16":"img/icon16.png"
},
"browser_action":{
"default_icon":{
"16":"img/icon16.png"
},
"default_title":"天气预报",
"default_popup":"popup.html"
},
"options_page":"options.html",
"permissions":[
"https://free-api.heweather.com/s6/weather/now?*"
]
}
栗子里面使用的API是和风天气,注册下就可以免费使用。
根据上面我们的json配置,需要有两个页面: options.html
popup.html
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>设定城市</title>
</head>
<body>
<input type="text" name="city" id="city" placeholder="请输入您所在的城市,默认泰安">
<input type="button" id="save" value="保存">
</body>
</html>
<script type="text/javascript" src="options.js"></script>
options.js
var city = document.getElementById('city');
var save = document.getElementById('save');
var value = localStorage.city || '泰安';
city.value = value;
save.onclick = function(){
localStorage.city = city.value;
alert('保存成功');
}
我们默认使用一个地址,然后将用户提交的地址,保存在localStorage
中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>天气</title>
<style>
#tianqi{
min-width:200px;
min-height:50px;
}
</style>
</head>
<body>
<div id="tianqi">
</div>
</body>
</html>
<script type="text/javascript" src="popup.js"></script>
popup.js
var request = function(url,cb){
var xhr = new XMLHttpRequest();
xhr.open('GET',url);
xhr.onreadystatechange = function(){
if(xhr.readyState ==4 && xhr.status == 200){
cb(xhr.responseText);
}
}
xhr.send();
}
var url = 'https://free-api.heweather.com/s6/weather/now';
var city = localStorage.city || '泰安';
var key = '注册后的KEY';
url = url + '?location='+city+'&key='+key;
request(url,function( res ){
var tianqi = document.getElementById('tianqi');
var obj = JSON.parse(res);
console.log(obj);
obj = obj.HeWeather6[0];
var html = '当前地区:'+obj.basic.location+',天气:'+obj.now.cond_txt+',风向:'+obj.now.wind_dir;
tianqi.innerHTML = html;
});
转载请注明出处: https://chrunlee.cn/article/chrome-learn-5.html