OSDN Git Service

fix api bug && delete no use console.log
[bytom/Byone.git] / src / background / index.js
1 console.log("This is BACKGROUND page!");
2
3 import bytom from "./bytom";
4 import query from "./query";
5 import account from "./account";
6 import transaction from "./transaction";
7
8 const ASSET_BTM =
9   "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
10
11 var globalAccounts = [];
12
13 function refreshBalances() {
14   globalAccounts.forEach(account => {
15     bytom.accounts.listAddressUseServer(account.guid).then(addresses => {
16       let balance = 0;
17       addresses.forEach(item => {
18         if (item.balances != null) {
19           item.balances.forEach(asset => {
20             if (asset.asset == ASSET_BTM) {
21               balance += asset.balance;
22             }
23           });
24         }
25       });
26
27       if (account.balance != balance) {
28         account.balance = balance / 100000000;
29       }
30     });
31   });
32 }
33
34 function refreshAccounts(success) {
35   bytom.accounts
36     .listAccountUseServer()
37     .then(accounts => {
38       console.log("refreshAccounts", accounts);
39       globalAccounts = accounts;
40       globalAccounts.forEach(account => {
41         if (account.balance == null) {
42           account.balance = 0;
43         }
44       });
45       success();
46     })
47     .catch(error => {
48       console.log(error);
49     });
50 }
51 refreshAccounts(refreshBalances);
52 setInterval(refreshBalances, 10000);
53
54 var bytomQuery = new query(bytom);
55 var bytomAccount = new account(bytom);
56 var bytomTransaction = new transaction(bytom);
57 bytomAccount.list = function() {
58   let retPromise = new Promise((resolve, reject) => {
59     refreshAccounts(() => {
60       refreshBalances();
61       resolve(globalAccounts);
62     });
63   });
64   return retPromise;
65 };
66
67 window.bytomSystem = bytom;
68 window.bytomQuery = bytomQuery;
69 window.bytomAccount = bytomAccount;
70 window.bytomTransaction = bytomTransaction;
71
72 chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
73   console.log("收到来自content-script的消息:");
74   console.log(request);
75   console.log(sender);
76   console.log(sendResponse);
77   // sendResponse("我是后台,我已收到你的消息:" + JSON.stringify(request));
78
79   if (request.bty == "transfer") {
80     var optionsUrl = chrome.extension.getURL("pages/prompt.html");
81     console.log(optionsUrl);
82     chrome.tabs.query({ url: optionsUrl }, (tabs) => {
83         console.log(22, tabs)
84         chrome.windows.create({ url: optionsUrl, type: "popup", width: 350, height: 625, left: 0 }, ()=>{
85           chrome.extension.sendMessage(  {cmd: "来自前台页面的主动调用"}, function(response) {  console.log(123, response); }  );//测试前台掉后台
86         });
87         
88     });
89   }
90 });