fe-background.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. /**
  2. * FE-Helper后台运行程序
  3. * @author [email protected]
  4. */
  5. var BgPageInstance = (function () {
  6. //各种元素的就绪情况
  7. var _readyState = {
  8. css: false,
  9. js: false,
  10. html: true,
  11. allDone: false
  12. };
  13. //侦测的interval
  14. var _detectInterval = null;
  15. //侦测就绪情况
  16. var _detectReadyState = function () {
  17. _detectInterval = window.setInterval(function () {
  18. if (_readyState.css && _readyState.js && _readyState.html) {
  19. _readyState.allDone = true;
  20. window.clearInterval(_detectInterval);
  21. }
  22. }, 100);
  23. };
  24. /**
  25. * 执行前端FCPHelper检测
  26. */
  27. var _doFcpDetect = function (tab) {
  28. //所有元素都准备就绪
  29. if (_readyState.allDone) {
  30. chrome.tabs.sendMessage(tab.id, {
  31. type: MSG_TYPE.BROWSER_CLICKED,
  32. event: MSG_TYPE.FCP_HELPER_DETECT
  33. });
  34. } else {
  35. //正在准备数据,请稍等...
  36. //显示桌面提醒
  37. baidu.feNotification.notifyText({
  38. message: "正在准备数据,请稍等..."
  39. });
  40. }
  41. };
  42. /**
  43. * 执行栅格检测
  44. */
  45. var _doGridDetect = function (tab) {
  46. chrome.tabs.sendMessage(tab.id, {
  47. type: MSG_TYPE.BROWSER_CLICKED,
  48. event: MSG_TYPE.GRID_DETECT
  49. });
  50. };
  51. /**
  52. * 提醒层 缓存
  53. * @type {Array}
  54. */
  55. var _notificationCache = [];
  56. /**
  57. * 查看页面wpo信息
  58. */
  59. var _showPageWpoInfo = function (wpoInfo) {
  60. chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
  61. var tab = tabs[0];
  62. try {
  63. _notificationCache[tab.id].cancel();
  64. } catch (e) {
  65. }
  66. if (!wpoInfo) {
  67. baidu.feNotification.notifyText({
  68. message: "对不起,检测失败"
  69. });
  70. } else {
  71. if (window.webkitNotifications && webkitNotifications.createHTMLNotification) {
  72. baidu.feNotification.notifyHtml("template/fehelper_wpo.html?" + JSON.stringify(wpoInfo));
  73. } else {
  74. chrome.tabs.create({
  75. url: "template/fehelper_wpo.html?" + JSON.stringify(wpoInfo),
  76. active: true
  77. });
  78. }
  79. }
  80. });
  81. };
  82. /**
  83. * 获取页面wpo信息
  84. * @return {[type]}
  85. */
  86. var _getPageWpoInfo = function () {
  87. chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
  88. var tab = tabs[0];
  89. //显示桌面提醒
  90. _notificationCache[tab.id] = baidu.feNotification.notifyText({
  91. message: "正在统计,请稍后...",
  92. autoClose: false
  93. });
  94. chrome.tabs.sendMessage(tab.id, {
  95. type: MSG_TYPE.GET_PAGE_WPO_INFO
  96. });
  97. });
  98. };
  99. /**
  100. * 执行JS Tracker
  101. * @private
  102. */
  103. var _doJsTracker = function () {
  104. chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
  105. var tab = tabs[0];
  106. chrome.tabs.executeScript(tab.id, {
  107. code: "void function(t,r,a,c,k){t.tracker_type='bm';t.tracker_uid='fehelper';"
  108. + "(k=t.TrackerGlobalEvent)?k.f(r):[(k=t[a]('script')).charset='utf-8',"
  109. + "k.src='http://www.ucren.com/'+c+'/'+c+'.js?'+Math.random(),"
  110. + "t.documentElement.appendChild(k)]}(document,'TrackerJSLoad','createElement','tracker') ",
  111. allFrames: false,
  112. runAt: 'document_end'
  113. });
  114. });
  115. };
  116. /**
  117. * 代码压缩工具
  118. * @private
  119. */
  120. var _goCompressTool = function () {
  121. var url = "http://www.baidufe.com/fehelper/codecompress.html";
  122. chrome.tabs.query({windowId: chrome.windows.WINDOW_ID_CURRENT}, function (tabs) {
  123. var isOpened = false;
  124. var tabId;
  125. var reg = new RegExp("fehelper.*codecompress.html$", "i");
  126. for (var i = 0, len = tabs.length; i < len; i++) {
  127. if (reg.test(tabs[i].url)) {
  128. isOpened = true;
  129. tabId = tabs[i].id;
  130. break;
  131. }
  132. }
  133. if (!isOpened) {
  134. chrome.tabs.create({
  135. url: url,
  136. active: true
  137. });
  138. } else {
  139. chrome.tabs.update(tabId, {highlighted: true});
  140. }
  141. });
  142. };
  143. /**
  144. * 创建或更新成功执行的动作
  145. * @param evt
  146. * @param content
  147. * @private
  148. */
  149. var _tabUpdatedCallback = function (evt, content) {
  150. return function (newTab) {
  151. if (content) {
  152. chrome.tabs.sendMessage(newTab.id, {
  153. type: MSG_TYPE.TAB_CREATED_OR_UPDATED,
  154. content: content,
  155. event: evt
  156. });
  157. }
  158. };
  159. };
  160. /**
  161. * 打开对应文件,运行该Helper
  162. * @param tab
  163. * @param file
  164. * @param txt
  165. * @private
  166. */
  167. var _openFileAndRun = function (tab, file, txt) {
  168. chrome.tabs.query({windowId: chrome.windows.WINDOW_ID_CURRENT}, function (tabs) {
  169. var isOpened = false;
  170. var tabId;
  171. var reg = new RegExp("^chrome.*" + file + ".html$", "i");
  172. for (var i = 0, len = tabs.length; i < len; i++) {
  173. if (reg.test(tabs[i].url)) {
  174. isOpened = true;
  175. tabId = tabs[i].id;
  176. break;
  177. }
  178. }
  179. if (!isOpened) {
  180. chrome.tabs.create({
  181. url: 'template/fehelper_' + file + '.html',
  182. active: true
  183. }, _tabUpdatedCallback(file, txt));
  184. } else {
  185. chrome.tabs.update(tabId, {highlighted: true}, _tabUpdatedCallback(file, txt));
  186. }
  187. });
  188. };
  189. /**
  190. * 根据给定参数,运行对应的Helper
  191. */
  192. var _runHelper = function (config) {
  193. chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
  194. var tab = tabs[0];
  195. // 如果是采用独立文件方式访问,直接打开该页面即可
  196. if (config.useFile == '1') {
  197. _openFileAndRun(tab, config.msgType);
  198. } else {
  199. switch (config.msgType) {
  200. //fcphelper检测
  201. case MSG_TYPE.FCP_HELPER_DETECT:
  202. _doFcpDetect(tab);
  203. break;
  204. //栅格检测
  205. case MSG_TYPE.GRID_DETECT:
  206. _doGridDetect(tab);
  207. break;
  208. //查看网页加载时间
  209. case MSG_TYPE.SHOW_PAGE_LOAD_TIME:
  210. _getPageWpoInfo();
  211. break;
  212. //js tracker
  213. case MSG_TYPE.JS_TRACKER:
  214. _doJsTracker();
  215. break;
  216. //代码压缩
  217. case MSG_TYPE.CODE_COMPRESS:
  218. _goCompressTool();
  219. break;
  220. }
  221. }
  222. });
  223. };
  224. /**
  225. * 创建扩展专属的右键菜单
  226. */
  227. var _createContextMenu = function () {
  228. _removeContextMenu();
  229. baidu.contextMenuId = chrome.contextMenus.create({
  230. title: "FeHelper",
  231. contexts: ['page', 'selection', 'editable', 'link'],
  232. documentUrlPatterns:['http://*/*','https://*/*']
  233. });
  234. chrome.contextMenus.create({
  235. title: "JSON格式化",
  236. contexts: ['page', 'selection', 'editable'],
  237. parentId: baidu.contextMenuId,
  238. onclick: function (info, tab) {
  239. chrome.tabs.executeScript(tab.id, {
  240. code: '(' + (function () {
  241. return window.getSelection().toString();
  242. }).toString() + ')()',
  243. allFrames: false
  244. }, function (txt) {
  245. _openFileAndRun(tab, 'jsonformat', txt);
  246. });
  247. }
  248. });
  249. chrome.contextMenus.create({
  250. type: 'separator',
  251. contexts: ['all'],
  252. parentId: baidu.contextMenuId
  253. });
  254. chrome.contextMenus.create({
  255. title: "字符串编解码",
  256. contexts: ['page', 'selection', 'editable'],
  257. parentId: baidu.contextMenuId,
  258. onclick: function (info, tab) {
  259. chrome.tabs.executeScript(tab.id, {
  260. code: '(' + (function () {
  261. return window.getSelection().toString();
  262. }).toString() + ')()',
  263. allFrames: false
  264. }, function (txt) {
  265. _openFileAndRun(tab, 'endecode', txt);
  266. });
  267. }
  268. });
  269. chrome.contextMenus.create({
  270. type: 'separator',
  271. contexts: ['all'],
  272. parentId: baidu.contextMenuId
  273. });
  274. chrome.contextMenus.create({
  275. title: "生成二维码",
  276. contexts: ['page', 'selection', 'editable', 'link'],
  277. parentId: baidu.contextMenuId,
  278. onclick: function (info, tab) {
  279. chrome.tabs.executeScript(tab.id, {
  280. code: '(' + (function () {
  281. return window.getSelection().toString() || location.href;
  282. }).toString() + ')()',
  283. allFrames: false
  284. }, function (txt) {
  285. _openFileAndRun(tab, 'qrcode', txt);
  286. });
  287. }
  288. });
  289. chrome.contextMenus.create({
  290. type: 'separator',
  291. contexts: ['all'],
  292. parentId: baidu.contextMenuId
  293. });
  294. chrome.contextMenus.create({
  295. title: "代码格式化",
  296. contexts: ['page', 'selection', 'editable'],
  297. parentId: baidu.contextMenuId,
  298. onclick: function (info, tab) {
  299. chrome.tabs.executeScript(tab.id, {
  300. code: '(' + (function () {
  301. return window.getSelection().toString();
  302. }).toString() + ')()',
  303. allFrames: false
  304. }, function (txt) {
  305. _openFileAndRun(tab, 'codebeautify', txt);
  306. });
  307. }
  308. });
  309. chrome.contextMenus.create({
  310. type: 'separator',
  311. contexts: ['all'],
  312. parentId: baidu.contextMenuId
  313. });
  314. chrome.contextMenus.create({
  315. title: "代码压缩",
  316. contexts: ['page', 'selection', 'editable'],
  317. parentId: baidu.contextMenuId,
  318. onclick: function (info, tab) {
  319. _goCompressTool();
  320. }
  321. });
  322. };
  323. /**
  324. * 移除扩展专属的右键菜单
  325. */
  326. var _removeContextMenu = function () {
  327. if (!baidu.contextMenuId) return;
  328. chrome.contextMenus.remove(baidu.contextMenuId);
  329. baidu.contextMenuId = null;
  330. };
  331. /**
  332. * 创建或移除扩展专属的右键菜单
  333. */
  334. var _createOrRemoveContextMenu = function () {
  335. //管理右键菜单
  336. if (baidu.feOption.getOptionItem('opt_item_contextMenus') !== 'false') {
  337. _createContextMenu();
  338. } else {
  339. _removeContextMenu();
  340. }
  341. };
  342. /**
  343. * 接收来自content_scripts发来的消息
  344. */
  345. var _addExtensionListener = function () {
  346. chrome.runtime.onMessage.addListener(function (request, sender, callback) {
  347. //处理CSS的请求
  348. if (request.type == MSG_TYPE.GET_CSS) {
  349. //直接AJAX获取CSS文件内容
  350. baidu.network.readFileContent(request.link, callback);
  351. }
  352. //处理JS的请求
  353. else if (request.type == MSG_TYPE.GET_JS) {
  354. //直接AJAX获取JS文件内容
  355. baidu.network.readFileContent(request.link, callback);
  356. }
  357. //处理HTML的请求
  358. else if (request.type == MSG_TYPE.GET_HTML) {
  359. //直接AJAX获取JS文件内容
  360. baidu.network.readFileContent(request.link, callback);
  361. }
  362. //处理cookie
  363. else if (request.type == MSG_TYPE.GET_COOKIE) {
  364. baidu.network.getCookies(request, callback);
  365. }
  366. //移除cookie
  367. else if (request.type == MSG_TYPE.REMOVE_COOKIE) {
  368. baidu.network.removeCookie(request, callback);
  369. }
  370. //设置cookie
  371. else if (request.type == MSG_TYPE.SET_COOKIE) {
  372. baidu.network.setCookie(request, callback);
  373. }
  374. //CSS准备就绪
  375. else if (request.type == MSG_TYPE.CSS_READY) {
  376. _readyState.css = true;
  377. }
  378. //JS准备就绪
  379. else if (request.type == MSG_TYPE.JS_READY) {
  380. _readyState.js = true;
  381. }
  382. //HTML准备就绪
  383. else if (request.type == MSG_TYPE.HTML_READY) {
  384. _readyState.html = true;
  385. }
  386. //提取配置项
  387. else if (request.type == MSG_TYPE.GET_OPTIONS) {
  388. baidu.feOption.doGetOptions(request.items, callback);
  389. }
  390. //保存配置项
  391. else if (request.type == MSG_TYPE.SET_OPTIONS) {
  392. baidu.feOption.doSetOptions(request.items, callback);
  393. //管理右键菜单
  394. _createOrRemoveContextMenu();
  395. }
  396. //保存当前网页加载时间
  397. else if (request.type == MSG_TYPE.CALC_PAGE_LOAD_TIME) {
  398. _showPageWpoInfo(request.wpo);
  399. }
  400. // 从popup中点过来的
  401. else if (request.type == MSG_TYPE.FROM_POPUP) {
  402. _runHelper(request.config);
  403. }
  404. return true;
  405. });
  406. };
  407. /**
  408. * 初始化
  409. */
  410. var _init = function () {
  411. _addExtensionListener();
  412. _detectReadyState();
  413. _createOrRemoveContextMenu();
  414. };
  415. return {
  416. init: _init,
  417. runHelper: _runHelper
  418. };
  419. })();
  420. //初始化
  421. BgPageInstance.init();