-
Notifications
You must be signed in to change notification settings - Fork 5
/
background.js
102 lines (88 loc) · 2.88 KB
/
background.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*Global variables*/
var notificationCache = {};
var checkInterval = 1000;
var reShowInterval = 5000;
/**
* Delete cache, so all notification will be sent
*/
var clearUpNotificationCache = function(){
notificationCache = {};
};
/**
* Binding `onClick` function to notification,
* when clicking, it will bring you to `WeChat` tab
* @param tab -- tab that contains `WeChat`
* @param notification -- Desktop notification object
*/
var bindTab2Notification = function(tab, notification){
notification.onclick = function(){
chrome.tabs.update(tab.id, {selected: true});
clearUpNotificationCache();
};
};
/**
* If the notification is occurred after user checked wechat,
* it will appear
* @param tab -- tab that contains `WeChat`
* @param nickname -- user's nickname, just used for identify
* @param notification -- Desktop notification object
*/
var showNotification = function(tab, nickname, notification){
if (!notificationCache[nickname] || (new Date() - notificationCache[nickname])>reShowInterval){
notificationCache[nickname] = new Date();
bindTab2Notification(tab, notification);
notification.show();
}
};
/**
* Construct desktop notification, and shows it
* @param tab -- tab that contains `WeChat`
* @param avatar -- users' avatar url, currently not working when construct
* @param title -- currently is user's nickname
* @param message -- body text of notification
*/
var constructNotification = function(tab, avatar, title, message){
var notification = webkitNotifications.createNotification(
avatar, title, message
);
showNotification(tab, title, notification);
};
/**
* Get unread list from content page, and do the notification stuff
* @param tab -- tab that contains `WeChat`
*/
var getUnReadList = function(tab){
chrome.tabs.executeScript(tab.id, {'file':'wechat.js'}, function(){
chrome.tabs.sendMessage(tab.id, {'method':'getUnReadList'}, function(response){
var unReadList = response.unReadList;
for(var nickname in unReadList){
constructNotification(
tab,
unReadList[nickname].avatar,
nickname,
'You got '+unReadList[nickname].unRead+' messages'
);
}
});
});
};
/**
* This will be called each time, in order to make sure wechat is still open
*/
var getWeChatTab = function(){
chrome.tabs.query({'url':'https://web.wechatapp.com/'}, function(tabs){
if(tabs.length){
getUnReadList(tabs[0]);
}else{
chrome.tabs.query({'url':'https://wx.qq.com/'}, function(tabs){
if(tabs.length){
getUnReadList(tabs[0]);
}
});
}
});
};
var workFlow = function(){
setInterval(getWeChatTab, checkInterval);
};
workFlow();