background.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. /**
  2. * FeJson后台运行程序
  3. * @author zhaoxianlie
  4. */
  5. import MSG_TYPE from '../static/js/common.js';
  6. import Settings from '../options/settings.js';
  7. import Menu from './menu.js';
  8. import Awesome from './awesome.js';
  9. import InjectTools from './inject-tools.js';
  10. import Monkey from './monkey.js';
  11. import Statistics from './statistics.js';
  12. let BgPageInstance = (function () {
  13. let FeJson = {
  14. notifyTimeoutId: -1
  15. };
  16. // 黑名单页面
  17. let blacklist = [
  18. /^https:\/\/chrome\.google\.com/
  19. ];
  20. // 全局缓存最新的客户端信息
  21. let FH_CLIENT_INFO = {};
  22. /**
  23. * 文本格式,可以设置一个图标和标题
  24. * @param {Object} options
  25. * @config {string} type notification的类型,可选值:html、text
  26. * @config {string} icon 图标
  27. * @config {string} title 标题
  28. * @config {string} message 内容
  29. */
  30. let notifyText = function (options) {
  31. let notifyId = 'FeJson-notify-id';
  32. clearTimeout(FeJson.notifyTimeoutId);
  33. if (options.closeImmediately) {
  34. return chrome.notifications.clear(notifyId);
  35. }
  36. if (!options.icon) {
  37. options.icon = "static/img/fe-48.png";
  38. }
  39. if (!options.title) {
  40. options.title = "温馨提示";
  41. }
  42. chrome.notifications.create(notifyId, {
  43. type: 'basic',
  44. title: options.title,
  45. iconUrl: chrome.runtime.getURL(options.icon),
  46. message: options.message
  47. });
  48. FeJson.notifyTimeoutId = setTimeout(() => {
  49. chrome.notifications.clear(notifyId);
  50. }, parseInt(options.autoClose || 3000, 10));
  51. };
  52. // 像页面注入css脚本
  53. let _injectContentCss = function(tabId,toolName,isDevTool){
  54. if(isDevTool){
  55. Awesome.getContentScript(toolName, true)
  56. .then(css => {
  57. InjectTools.inject(tabId, { css })
  58. });
  59. }else{
  60. InjectTools.inject(tabId, {files: [`${toolName}/content-script.css`]});
  61. }
  62. };
  63. // 往当前页面直接注入脚本,不再使用content-script的配置了
  64. let _injectContentScripts = function (tabId) {
  65. // FH工具脚本注入
  66. Awesome.getInstalledTools().then(tools => {
  67. // 注入js
  68. let jsTools = Object.keys(tools)
  69. .filter(tool => !tools[tool]._devTool
  70. && (tools[tool].contentScriptJs || tools[tool].contentScript));
  71. let jsCodes = [];
  72. jsTools.forEach((t, i) => {
  73. let func = `window['${t.replace(/-/g, '')}ContentScript']`;
  74. jsCodes.push(`(()=>{let func=${func};func&&func();})()`);
  75. });
  76. let jsFiles = jsTools.map(tool => `${tool}/content-script.js`);
  77. InjectTools.inject(tabId, {files: jsFiles,js: jsCodes.join(';')});
  78. });
  79. // 其他开发者自定义工具脚本注入======For FH DevTools
  80. Awesome.getInstalledTools().then(tools => {
  81. let list = Object.keys(tools).filter(tool => tools[tool]._devTool);
  82. // 注入js脚本
  83. list.filter(tool => (tools[tool].contentScriptJs || tools[tool].contentScript))
  84. .map(tool => Awesome.getContentScript(tool).then(js => {
  85. InjectTools.inject(tabId, { js });
  86. }));
  87. });
  88. };
  89. /**
  90. * 打开打赏弹窗
  91. * @param {string} toolName - 工具名称
  92. */
  93. chrome.gotoDonateModal = function (toolName) {
  94. chrome.tabs.query({currentWindow: true}, function (tabs) {
  95. Settings.getOptions((opts) => {
  96. let isOpened = false;
  97. let tabId;
  98. let reg = new RegExp("^chrome.*\\/options\\/index.html\\?donate_from=" + toolName + "$", "i");
  99. for (let i = 0, len = tabs.length; i < len; i++) {
  100. if (reg.test(tabs[i].url)) {
  101. isOpened = true;
  102. tabId = tabs[i].id;
  103. break;
  104. }
  105. }
  106. if (!isOpened) {
  107. let url = `/options/index.html?donate_from=${toolName}`;
  108. chrome.tabs.create({ url,active: true });
  109. } else {
  110. chrome.tabs.update(tabId, {highlighted: true}).then(tab => {
  111. chrome.tabs.reload(tabId);
  112. });
  113. }
  114. });
  115. });
  116. };
  117. /**
  118. * 动态运行工具
  119. * @param configs
  120. * @config tool 工具名称
  121. * @config withContent 默认携带的内容
  122. * @config query 请求参数
  123. * @config noPage 无页面模式
  124. * @constructor
  125. */
  126. chrome.DynamicToolRunner = async function (configs) {
  127. let tool = configs.tool || configs.page;
  128. let withContent = configs.withContent;
  129. let activeTab = null;
  130. let query = configs.query;
  131. // 如果是noPage模式,则表名只完成content-script的工作,直接发送命令即可
  132. if (configs.noPage) {
  133. let toolFunc = tool.replace(/-/g, '');
  134. chrome.tabs.query({active: true, currentWindow: true}, tabs => {
  135. let found = tabs.some(tab => {
  136. if (/^(http(s)?|file):\/\//.test(tab.url) && blacklist.every(reg => !reg.test(tab.url))) {
  137. let codes = `window['${toolFunc}NoPage'] && window['${toolFunc}NoPage'](${JSON.stringify(tab)});`;
  138. InjectTools.inject(tab.id, {js: codes});
  139. return true;
  140. }
  141. return false;
  142. });
  143. if (!found) {
  144. notifyText({
  145. message: '抱歉,此工具无法在当前页面使用!'
  146. });
  147. }
  148. });
  149. return;
  150. }
  151. chrome.tabs.query({currentWindow: true}, function (tabs) {
  152. activeTab = tabs.filter(tab => tab.active)[0];
  153. // 如果是二维码工具,且没有传入内容,则使用当前页面的URL
  154. if (tool === 'qr-code' && !withContent && activeTab) {
  155. withContent = activeTab.url;
  156. }
  157. Settings.getOptions((opts) => {
  158. let isOpened = false;
  159. let tabId;
  160. // 允许在新窗口打开
  161. if (String(opts['FORBID_OPEN_IN_NEW_TAB']) === 'true') {
  162. let reg = new RegExp("^chrome.*\\/" + tool + "\\/index.html" + (query ? "\\?" + query : '') + "$", "i");
  163. for (let i = 0, len = tabs.length; i < len; i++) {
  164. if (reg.test(tabs[i].url)) {
  165. isOpened = true;
  166. tabId = tabs[i].id;
  167. break;
  168. }
  169. }
  170. }
  171. if (!isOpened) {
  172. let url = `/${tool}/index.html` + (query ? "?" + query : '');
  173. chrome.tabs.create({
  174. url,
  175. active: true
  176. }).then(tab => { FeJson[tab.id] = { content: withContent }; });
  177. } else {
  178. chrome.tabs.update(tabId, {highlighted: true}).then(tab => {
  179. FeJson[tab.id] = { content: withContent };
  180. chrome.tabs.reload(tabId);
  181. });
  182. }
  183. });
  184. });
  185. };
  186. /**
  187. * 动态在icon处显示提示
  188. * @param tips
  189. * @private
  190. */
  191. let _animateTips = (tips) => {
  192. setTimeout(() => {
  193. chrome.action.setBadgeText({text: tips});
  194. setTimeout(() => {
  195. chrome.action.setBadgeText({text: ''});
  196. }, 2000);
  197. }, 3000);
  198. };
  199. /**
  200. * 插件图标点击后的默认动作
  201. * @param request
  202. * @param sender
  203. * @param callback
  204. */
  205. let browserActionClickedHandler = function (request, sender, callback) {
  206. chrome.DynamicToolRunner({
  207. tool: MSG_TYPE.JSON_FORMAT
  208. });
  209. // 记录工具使用
  210. Statistics.recordToolUsage(MSG_TYPE.JSON_FORMAT);
  211. };
  212. /**
  213. * 更新browser action的点击动作
  214. * @param action install / upgrade / offload
  215. * @param showTips 是否notify
  216. * @param menuOnly 只管理Menu
  217. * @private
  218. */
  219. let _updateBrowserAction = function (action, showTips, menuOnly) {
  220. if (!menuOnly) {
  221. // 如果有安装过工具,则显示Popup模式
  222. Awesome.getInstalledTools().then(tools => {
  223. if (Object.keys(tools).length > 1) {
  224. chrome.action.setPopup({ popup: '/popup/index.html' });
  225. } else {
  226. // 删除popup page
  227. chrome.action.setPopup({ popup: '' });
  228. // 否则点击图标,直接打开页面
  229. if (!chrome.action.onClicked.hasListener(browserActionClickedHandler)) {
  230. chrome.action.onClicked.addListener(browserActionClickedHandler);
  231. }
  232. }
  233. });
  234. if (action === 'offload') {
  235. _animateTips('-1');
  236. } else if(!!action) {
  237. _animateTips('+1');
  238. }
  239. } else {
  240. // 重绘菜单
  241. Menu.rebuild();
  242. }
  243. if (showTips) {
  244. let actionTxt = '';
  245. switch (action) {
  246. case 'install':
  247. actionTxt = '工具已「安装」成功,并已添加到弹出下拉列表,点击FeHelper图标可正常使用!';
  248. break;
  249. case 'offload':
  250. actionTxt = '工具已「卸载」成功,并已从弹出下拉列表中移除!';
  251. break;
  252. case 'menu-install':
  253. actionTxt = '已将此工具快捷方式加入到「右键菜单」中!';
  254. break;
  255. case 'menu-offload':
  256. actionTxt = '已将此工具快捷方式从「右键菜单」中移除!';
  257. break;
  258. default:
  259. actionTxt = '恭喜,操作成功!';
  260. }
  261. notifyText({
  262. message: actionTxt,
  263. autoClose: 2500
  264. });
  265. }
  266. };
  267. // 捕获当前页面可视区域
  268. let _captureVisibleTab = function (callback) {
  269. chrome.tabs.captureVisibleTab(null, {format: 'png', quality: 100}, uri => {
  270. callback && callback(uri);
  271. });
  272. };
  273. let _addScreenShotByPages = function(params,callback){
  274. chrome.tabs.captureVisibleTab(null, {format: 'png', quality: 100}, uri => {
  275. callback({ params, uri });
  276. });
  277. };
  278. let _showScreenShotResult = function(data){
  279. // 确保截图数据完整有效
  280. if (!data || !data.screenshots || !data.screenshots.length) {
  281. return;
  282. }
  283. chrome.DynamicToolRunner({
  284. tool: 'screenshot',
  285. withContent: data
  286. });
  287. };
  288. let _colorPickerCapture = function(params) {
  289. chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
  290. chrome.tabs.captureVisibleTab(null, {format: 'png'}, function (dataUrl) {
  291. let js = `window.colorpickerNoPage(${JSON.stringify({
  292. setPickerImage: true,
  293. pickerImage: dataUrl
  294. })})`;
  295. InjectTools.inject(tabs[0].id, { js });
  296. });
  297. });
  298. };
  299. let _codeBeautify = function(params){
  300. Awesome.StorageMgr.get('JS_CSS_PAGE_BEAUTIFY').then(val => {
  301. if(val !== '0') {
  302. let js = `window._codebutifydetect_('${params.fileType}')`;
  303. InjectTools.inject(params.tabId, { js });
  304. // 记录工具使用
  305. Statistics.recordToolUsage('code-beautify');
  306. }
  307. });
  308. };
  309. /**
  310. * 接收来自content_scripts发来的消息
  311. */
  312. let _addExtensionListener = function () {
  313. _updateBrowserAction();
  314. chrome.runtime.onMessage.addListener(function (request, sender, callback) {
  315. // 如果发生了错误,就啥都别干了
  316. if (chrome.runtime.lastError) {
  317. return true;
  318. }
  319. // 动态安装工具或者卸载工具,需要更新browserAction
  320. if (request.type === MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD) {
  321. _updateBrowserAction(request.action, request.showTips, request.menuOnly);
  322. callback && callback();
  323. }
  324. // 截屏
  325. else if (request.type === MSG_TYPE.CAPTURE_VISIBLE_PAGE) {
  326. _captureVisibleTab(callback);
  327. // 记录工具使用
  328. Statistics.recordToolUsage('screenshot');
  329. }
  330. // 直接处理content-script.js中的截图请求
  331. else if (request.type === 'fh-screenshot-capture-visible') {
  332. _captureVisibleTab(callback);
  333. // 记录工具使用
  334. Statistics.recordToolUsage('screenshot');
  335. }
  336. // 打开动态工具页面
  337. else if (request.type === MSG_TYPE.OPEN_DYNAMIC_TOOL) {
  338. chrome.DynamicToolRunner(request);
  339. // 记录工具使用
  340. if (request.page) {
  341. Statistics.recordToolUsage(request.page);
  342. }
  343. callback && callback();
  344. }
  345. // 打开其他页面
  346. else if (request.type === MSG_TYPE.OPEN_PAGE) {
  347. chrome.DynamicToolRunner({
  348. tool: request.page
  349. });
  350. // 记录工具使用
  351. if (request.page) {
  352. Statistics.recordToolUsage(request.page);
  353. }
  354. callback && callback();
  355. }
  356. // 任何事件,都可以通过这个钩子来完成
  357. else if (request.type === MSG_TYPE.DYNAMIC_ANY_THING) {
  358. switch(request.thing){
  359. case 'save-options':
  360. notifyText({
  361. message: '配置修改已生效,请继续使用!',
  362. autoClose: 2000
  363. });
  364. break;
  365. case 'trigger-screenshot':
  366. // 处理从popup触发的截图请求
  367. if (request.tabId) {
  368. _triggerScreenshotTool(request.tabId);
  369. } else {
  370. chrome.DynamicToolRunner({
  371. tool: 'screenshot',
  372. noPage: true
  373. });
  374. }
  375. // 记录工具使用
  376. Statistics.recordToolUsage('screenshot');
  377. break;
  378. case 'request-jsonformat-options':
  379. Awesome.StorageMgr.get(request.params).then(result => {
  380. Object.keys(result).forEach(key => {
  381. if (['MAX_JSON_KEYS_NUMBER', 'JSON_FORMAT_THEME'].includes(key)) {
  382. result[key] = parseInt(result[key]);
  383. } else {
  384. result[key] = (result[key] !== 'false');
  385. }
  386. });
  387. callback && callback(result);
  388. });
  389. return true; // 这个返回true是非常重要的!!!要不然callback会拿不到结果
  390. case 'save-jsonformat-options':
  391. Awesome.StorageMgr.set(request.params).then(() => {
  392. callback && callback();
  393. });
  394. return true;
  395. case 'toggle-jsonformat-options':
  396. Awesome.StorageMgr.get('JSON_TOOL_BAR_ALWAYS_SHOW').then(result => {
  397. let show = result !== false;
  398. Awesome.StorageMgr.set('JSON_TOOL_BAR_ALWAYS_SHOW',!show).then(() => {
  399. callback && callback(!show);
  400. });
  401. });
  402. // 记录工具使用
  403. Statistics.recordToolUsage('json-format');
  404. return true; // 这个返回true是非常重要的!!!要不然callback会拿不到结果
  405. case 'code-beautify':
  406. _codeBeautify(request.params);
  407. break;
  408. case 'close-beautify':
  409. Awesome.StorageMgr.set('JS_CSS_PAGE_BEAUTIFY',0);
  410. break;
  411. case 'qr-decode':
  412. chrome.DynamicToolRunner({
  413. withContent: request.params.uri,
  414. tool: 'qr-code',
  415. query: `mode=decode`
  416. });
  417. // 记录工具使用
  418. Statistics.recordToolUsage('qr-code');
  419. break;
  420. case 'request-page-content':
  421. request.params = FeJson[request.tabId];
  422. delete FeJson[request.tabId];
  423. break;
  424. case 'set-page-timing-data':
  425. chrome.DynamicToolRunner({
  426. tool: 'page-timing',
  427. withContent: request.wpoInfo
  428. });
  429. // 记录工具使用
  430. Statistics.recordToolUsage('page-timing');
  431. break;
  432. case 'color-picker-capture':
  433. _colorPickerCapture(request.params);
  434. // 记录工具使用
  435. Statistics.recordToolUsage('color-picker');
  436. break;
  437. case 'add-screen-shot-by-pages':
  438. _addScreenShotByPages(request.params,callback);
  439. // 记录工具使用
  440. Statistics.recordToolUsage('screenshot');
  441. return true;
  442. case 'page-screenshot-done':
  443. _showScreenShotResult(request.params);
  444. break;
  445. case 'request-monkey-start':
  446. Monkey.start(request.params);
  447. // 记录工具使用
  448. Statistics.recordToolUsage('page-monkey');
  449. break;
  450. case 'inject-content-css':
  451. _injectContentCss(sender.tab.id,request.tool,!!request.devTool);
  452. break;
  453. case 'open-options-page':
  454. chrome.runtime.openOptionsPage();
  455. break;
  456. case 'open-donate-modal':
  457. chrome.gotoDonateModal(request.params.toolName);
  458. break;
  459. case 'load-local-script':
  460. // 处理加载JSON格式化相关脚本的请求
  461. fetch(request.script)
  462. .then(response => response.text())
  463. .then(scriptContent => {
  464. callback && callback(scriptContent);
  465. })
  466. .catch(error => {
  467. console.error('加载脚本失败:', error);
  468. callback && callback(null);
  469. });
  470. return true; // 异步响应需要返回true
  471. case 'statistics-tool-usage':
  472. // 埋点:自动触发json-format-auto
  473. Statistics.recordToolUsage(request.params.tool_name,request.params);
  474. break;
  475. }
  476. callback && callback(request.params);
  477. } else {
  478. callback && callback();
  479. }
  480. return true;
  481. });
  482. // 每开一个窗口,都向内容脚本注入一个js,绑定tabId
  483. chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  484. if (String(changeInfo.status).toLowerCase() === "complete") {
  485. if(/^(http(s)?|file):\/\//.test(tab.url) && blacklist.every(reg => !reg.test(tab.url))){
  486. InjectTools.inject(tabId, { js: `window.__FH_TAB_ID__=${tabId};` });
  487. _injectContentScripts(tabId);
  488. }
  489. }
  490. });
  491. // 安装与更新
  492. chrome.runtime.onInstalled.addListener(({reason, previousVersion}) => {
  493. switch (reason) {
  494. case 'install':
  495. chrome.runtime.openOptionsPage();
  496. // 记录新安装用户
  497. Statistics.recordInstallation();
  498. break;
  499. case 'update':
  500. _animateTips('+++1');
  501. // 记录更新安装
  502. Statistics.recordUpdate(previousVersion);
  503. if (previousVersion === '2019.12.2415') {
  504. notifyText({
  505. message: '历尽千辛万苦,FeHelper已升级到最新版本,可以到插件设置页去安装旧版功能了!',
  506. autoClose: 5000
  507. });
  508. }
  509. // 从V2020.02.1413版本开始,本地的数据存储大部分迁移至chrome.storage.local
  510. // 这里需要对老版本升级过来的情况进行强制数据迁移
  511. let getAbsNum = num => parseInt(num.split(/\./).map(n => n.padStart(4, '0')).join(''), 10);
  512. // let preVN = getAbsNum(previousVersion);
  513. // let minVN = getAbsNum('2020.02.1413');
  514. // if (preVN < minVN) {
  515. // Awesome.makeStorageUnlimited();
  516. // setTimeout(() => chrome.runtime.reload(), 1000 * 5);
  517. // }
  518. break;
  519. }
  520. });
  521. // 卸载
  522. chrome.runtime.setUninstallURL(chrome.runtime.getManifest().homepage_url);
  523. };
  524. /**
  525. * 检查插件更新
  526. * @private
  527. */
  528. let _checkUpdate = function () {
  529. setTimeout(() => {
  530. chrome.runtime.requestUpdateCheck((status) => {
  531. if (status === "update_available") {
  532. chrome.runtime.reload();
  533. }
  534. });
  535. }, 1000 * 30);
  536. };
  537. /**
  538. * 初始化
  539. */
  540. let _init = function () {
  541. _checkUpdate();
  542. _addExtensionListener();
  543. // 添加截图工具直接命令 - 通过右键菜单触发
  544. chrome.contextMenus.onClicked.addListener((info, tab) => {
  545. if (info.menuItemId === 'fehelper-screenshot-page') {
  546. _triggerScreenshotTool(tab.id);
  547. // 记录工具使用
  548. Statistics.recordToolUsage('screenshot');
  549. }
  550. });
  551. // 创建截图工具右键菜单
  552. chrome.contextMenus.create({
  553. id: 'fehelper-screenshot-page',
  554. title: '网页截图',
  555. contexts: ['page']
  556. });
  557. // 初始化统计功能
  558. Statistics.init();
  559. Menu.rebuild();
  560. // 定期清理冗余的垃圾
  561. setTimeout(() => {
  562. Awesome.gcLocalFiles();
  563. }, 1000 * 10);
  564. };
  565. /**
  566. * 触发截图工具的执行
  567. * @param {number} tabId - 标签页ID
  568. */
  569. function _triggerScreenshotTool(tabId) {
  570. // 先尝试直接发送消息给content script
  571. chrome.tabs.sendMessage(tabId, {
  572. type: 'fh-screenshot-start'
  573. }).then(() => {
  574. // 成功触发
  575. }).catch(() => {
  576. // 如果发送消息失败,使用noPage模式
  577. chrome.DynamicToolRunner({
  578. tool: 'screenshot',
  579. noPage: true
  580. });
  581. });
  582. }
  583. // 监听options页面传递的客户端信息
  584. chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  585. if (request && request.type === 'clientInfo' && request.data) {
  586. FH_CLIENT_INFO = request.data;
  587. }
  588. });
  589. return {
  590. pageCapture: _captureVisibleTab,
  591. init: _init
  592. };
  593. })();
  594. BgPageInstance.init();