-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
90 lines (87 loc) · 2.19 KB
/
background.js
File metadata and controls
90 lines (87 loc) · 2.19 KB
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
var tabIds = {};
var tids = {};
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
var resp = {};
if (request.cmd === 'open') {
resp = null;
chrome.tabs.create({url:request.url,selected: false}, function(tab){
sendResponse({'id': tab.id});
});
}
else if (request.cmd === 'close') {
try {
chrome.tabs.remove(request.id);
}
catch(e){}
}
else if (request.cmd === 'setTimeout') {
var tidkey = request.tid + '-' + sender.tab.id;
if (tidkey in tids) {
clearTimeout(tids[tidkey]);
}
var tid = setTimeout(function(){
delete tids[tidkey];
sendResponse({state: 'complete'});
}, request.t);
tids[tidkey] = tid;
return;
}
else if (request.cmd === 'clearTimeout') {
var tidkey = request.tid + '-' + sender.tab.id;
clearTimeout(tids[tidkey]);
delete tids[tidkey];
}
else if (request.cmd === 'login') {
chrome.windows.getAll({populate:true},function(wins){
var hasPage = false;
$.asyncEach(wins, function(ind, win, done) {
if (win.tabs.some(function(tab){
if(tab.url.match(/^https?:\/\/kyfw\.12306\.cn\/otn\/view\/index\.html/)) {
chrome.tabs.update(tab.id, {url: tab.url});
return true;
}
return false;
})) {
hasPage = true;
done('complete');
return;
}
done('next');
}, function() {
if (!hasPage) {
chrome.tabs.create({url:"https://kyfw.12306.cn/otn/view/index.html",selected: true}, function(tab){ });
}
});
});
}
if(resp !== null)
sendResponse(resp);
});
$.asyncEach = function (obj, fun, complete) {
var keys = Object.keys(obj);
if (Array.isArray(obj)) {
keys = keys.map(function(elem){return elem-0});
}
var len = keys.length;
var keyInd = -1;
var retryCtn = 0;
done('next');
function done(state) {
if (state === 'complete') {
complete(Array.prototype.slice.call(arguments, 1));
return;
}
else if (state === 'next') {
retryCtn = 0;
keyInd++
}
else {
retryCtn++;
}
if (keyInd >= len) {
complete(Array.prototype.slice.call(arguments, 1));
return;
}
setTimeout(fun.bind(obj, keys[keyInd], obj[keys[keyInd]], done, retryCtn), 0);
}
};