background.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. export default defineBackground(() => {
  2. let currentTabId
  3. let arr = []
  4. let token = ''
  5. let userId = ''
  6. const url = import.meta.env.VITE_APP_BASE_API + '/behavior/user/adds'
  7. // Executed when background is loaded
  8. chrome.sidePanel
  9. .setPanelBehavior({ openPanelOnActionClick: true })
  10. .catch((error) => console.error(error))
  11. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  12. if (message.type === 'CLICK_EVENT') {
  13. if (token) {
  14. arr.push({
  15. ...message.data,
  16. userId:token
  17. })
  18. if (arr.length > 10) {
  19. fetch(url, {
  20. method: 'POST',
  21. headers: {
  22. 'Content-Type': 'application/json',
  23. 'Authorization': 'Bearer ' + token
  24. },
  25. body: JSON.stringify(arr.map(_ => ({ ..._, userId })))
  26. }).then(res => 1)
  27. arr = []
  28. }
  29. }
  30. }
  31. if (message.type === 'PAGE_INFO') {
  32. // 转发到侧边栏
  33. chrome.runtime.sendMessage({
  34. type: 'TO_SIDE_PANEL_PAGE_INFO',
  35. data: message.data
  36. })
  37. }
  38. if (message.type === 'FROM_CONTENT_TO_SEND_PAGE_FORM') {
  39. chrome.runtime.sendMessage({
  40. type: 'TO_SIDE_PANEL_FORM_INFO',
  41. data: message.data
  42. })
  43. }
  44. if (message.type === 'FROM_SIDE_PANEL_TO_ACTION') {
  45. chrome.tabs.query({ active: true }, (tabs) => {
  46. if (tabs.length === 0) return // 确保有活动标签页
  47. const tabId = tabs[0].id // 获取当前活动的 tabId
  48. chrome.tabs.sendMessage(
  49. tabId,
  50. { type: 'GET_TAG_ACTION', data: message.data },
  51. (response) => {
  52. if (chrome.runtime.lastError) {
  53. console.error('消息发送失败:', chrome.runtime.lastError.message)
  54. } else {
  55. console.log('收到 content script 响应:', response)
  56. console.log(response, 998)
  57. sendResponse(response)
  58. }
  59. }
  60. )
  61. })
  62. return true
  63. }
  64. if (message.type === 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM') {
  65. chrome.tabs.query({ active: true }, (tabs) => {
  66. if (tabs.length === 0) return // 确保有活动标签页
  67. const tabId = tabs[0].id // 获取当前活动的 tabId
  68. chrome.tabs.sendMessage(
  69. tabId,
  70. { type: 'GET_PAGE_FORM', data: 'Hello from background!' },
  71. (response) => {
  72. if (chrome.runtime.lastError) {
  73. console.error('消息发送失败:', chrome.runtime.lastError.message)
  74. } else {
  75. console.log('收到 content script 响应:', response)
  76. sendResponse(response)
  77. }
  78. return true
  79. }
  80. )
  81. })
  82. return true
  83. }
  84. if (message.type === 'FROM_SIDE_PANEL_TO_INPUT_FORM') {
  85. chrome.tabs.query({ active: true }, (tabs) => {
  86. if (tabs.length === 0) return // 确保有活动标签页
  87. const tabId = tabs[0].id // 获取当前活动的 tabId
  88. chrome.tabs.sendMessage(
  89. tabId,
  90. { type: 'INPUT_FORM', data: message.data },
  91. (response) => {
  92. if (chrome.runtime.lastError) {
  93. console.error('消息发送失败:', chrome.runtime.lastError.message)
  94. } else {
  95. console.log('收到 content script 响应:', response)
  96. sendResponse(response.data)
  97. }
  98. }
  99. )
  100. })
  101. return true
  102. }
  103. if (message.type === 'FROM_SIDE_PANEL_TO_GET_PAGE_INFO') {
  104. chrome.tabs.query({ active: true }, (tabs) => {
  105. if (tabs.length === 0) return // 确保有活动标签页
  106. const tabId = tabs[0].id // 获取当前活动的 tabId
  107. chrome.tabs.sendMessage(
  108. tabId,
  109. { type: 'GET_PAGE_INFO', data: 'Hello from background!' },
  110. (response) => {
  111. if (chrome.runtime.lastError) {
  112. console.error('消息发送失败:', chrome.runtime.lastError.message)
  113. } else {
  114. console.log(response, 777)
  115. console.log('收到 content script 响应:', response)
  116. sendResponse(response.data)
  117. }
  118. }
  119. )
  120. })
  121. return true
  122. }
  123. return true
  124. })
  125. let timer
  126. // chrome.tabs.onRemoved.addListener(function (...a) {
  127. // clearTimeout(timer)
  128. // timer = setTimeout(() => {
  129. // chrome.tabs.query({}, function (tabs) {
  130. // fetch(url, {
  131. // method: 'POST',
  132. // headers: {
  133. // 'Content-Type': 'application/json',
  134. // },
  135. // body: JSON.stringify(arr)
  136. // }).then(res => 1)
  137. // arr = []
  138. // });
  139. // }, 0)
  140. // });
  141. chrome.storage.onChanged.addListener((changes, areaName) => {
  142. console.log('[Storage Changed] Area:', areaName);
  143. // 遍历所有被修改的键
  144. for (const [key, { oldValue, newValue }] of Object.entries(changes)) {
  145. console.log(key);
  146. if (key === 'token') {
  147. token = newValue
  148. if (!newValue) {
  149. chrome.runtime.sendMessage({
  150. type: 'USER_LOGOUT',
  151. }, function (response) {
  152. });
  153. break
  154. }
  155. }
  156. if (key === 'userInfo') {
  157. if (!newValue) {
  158. chrome.runtime.sendMessage({
  159. type: 'USER_LOGOUT',
  160. }, function (response) {
  161. });
  162. break
  163. }
  164. userId = JSON.parse(newValue).id
  165. }
  166. }
  167. });
  168. chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  169. if (changeInfo.status === 'complete' && tab.url) {
  170. chrome.runtime.sendMessage({
  171. type: 'TO_SIDE_PANEL_PAGE_CHANGE',
  172. data: tab
  173. })
  174. currentTabId = tab.id
  175. }
  176. })
  177. chrome.tabs.onActivated.addListener((activeInfo) => {
  178. chrome.tabs.get(activeInfo.tabId, (tab) => {
  179. if (chrome.runtime.lastError) {
  180. console.error(chrome.runtime.lastError)
  181. return
  182. }
  183. chrome.runtime.sendMessage({
  184. type: 'TO_SIDE_PANEL_PAGE_CHANGE',
  185. data: tab
  186. })
  187. console.log('用户切换到新 Tab,URL:', tab)
  188. currentTabId = tab.id
  189. })
  190. })
  191. })
  192. // Allows users to open the side panel by clicking on the action toolbar icon