這次會整合先前介紹過的 xhr 、 alarms 、 notifications 三個特性,
做出一但有新的鐵人賽文章, 就會出現通知來提醒使用者.
manifest.json
{
"manifest_version": 2,
"name": "ironman6",
"version": "1.0",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [
"alarms",
"notifications",
"http://ithelp.ithome.com.tw/*"
]
}
background.js
chrome.alarms.create('ironman6', {
periodInMinutes : 1,
when : Date.now()
});
chrome.alarms.onAlarm.addListener(getRSS);
function getRSS(alarm){
var xhr = new XMLHttpRequest();
var url = 'http://ithelp.ithome.com.tw/rss/question?tag=%E9%90%B5%E4%BA%BA%E8%B3%BD';
xhr.open('GET', url);
xhr.onload = function(e) {
if (this.status === 200) {
var xml = this.responseXML;
var time = xml.querySelector('lastBuildDate').textContent;
if (time === localStorage['time']){return;}
localStorage['time'] = time;
var item = xml.querySelectorAll('item');
var list = [];
for (var i = 0; i < 5; i++){
var rss = item[i];
var title = (i + 1) + ". " + rss.querySelector('title').textContent;
var desc = rss.querySelector('description').textContent;
var link = rss.querySelector('link').textContent;
list.push({title: title, message: desc});
}
showList(list);
}
};
xhr.send();
}
function showList(myItems){
chrome.notifications.create(
'Notifier' + Date.now(), {
type: 'list',
iconUrl: 'http://ithelp.ithome.com.tw/ironman6/img/ironman6_logo.png',
title: '鐵人賽最新文章',
message: 'Day 19',
items: myItems
},
function(notificationId) {
console.log(notificationId);
}
);
}