forked from tamerh/mybinancefirefox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
108 lines (79 loc) · 2.17 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
103
104
105
106
107
108
var baseEndpoint = "https://api.binance.com/api/v3/userDataStream";
var apiKey = "";
var listenKey = "";
var binanceSocket = null;
var connected = false;
var retryFrequency = 10000;
var extendFrequency = retryFrequency * 6 * 10;
var initialized = false;
init();
function init() {
var gettingApiKey = browser.storage.sync.get('myBinanceApiKey');
gettingApiKey.then((res) => {
if (typeof (res.myBinanceApiKey) !== 'undefined') {
apiKey = res.myBinanceApiKey;
listenBinance();
if (!initialized) {
initialized = true;
checkConnectionPeriodically();
}
}
});
}
browser.storage.onChanged.addListener(function (changes, areaName) {
console.log("local storage changed");
init();
});
function listenBinance() {
if (binanceSocket != null) {
console.log("closing existing socket connection");
binanceSocket.close();
}
fetch(baseEndpoint, {
method: 'POST',
headers: {
'X-MBX-APIKEY': apiKey,
}
})
.then((response) => response.json())
.then((data) => {
listenKey = data.listenKey;
console.log('Success:', data);
binanceSocket = new WebSocket("wss://stream.binance.com:9443/ws/" + listenKey);
connected = true;
binanceSocket.onmessage = function (event) {
var eventData = JSON.parse(event.data);
console.log(eventData);
if (eventData.e && eventData.e == "executionReport") {
browser.notifications.create({
"type": "basic",
"title": "Binance Order Update",
"message": eventData.s,
"iconUrl": "icons/48.png"
});
}
}
binanceSocket.onerror = function (event) {
console.log(event);
connected = false;
}
})
.catch((error) => {
console.log(event);
connected = false;
});
}
function checkConnectionPeriodically() {
// retry connetion if it failed
var extendTimer = 0;
setInterval(function () {
if (!connected) {
listenBinance();
}
extendTimer = extendTimer + retryFrequency;
if (extendTimer >= extendFrequency) {
connected = false;
extendTimer = 0;
}
}, retryFrequency);
}