| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960 |
- /**
- * FE-Helper后台运行程序
- * @author zhaoxianlie
- */
- var BgPageInstance = (function () {
- let MSG_TYPE = Tarp.require('../static/js/msg_type');
- let Settings = Tarp.require('../options/settings');
- let Network = Tarp.require('../background/network');
- let PageCapture = Tarp.require('../page-capture/capture-api')(MSG_TYPE);
- let feHelper = {
- codeStandardMgr: {},
- ajaxDebuggerMgr: {},
- csDetectIntervals: [],
- manifest: chrome.runtime.getManifest(),
- notifyTimeoutId: -1
- };
- let devToolsDetected = false;
- //侦测就绪情况
- let _detectReadyState = function (getType, callback) {
- chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- let tabId = tabs[0].id;
- feHelper.codeStandardMgr[tabId][getType] = true;
- if (feHelper.codeStandardMgr[tabId].css && feHelper.codeStandardMgr[tabId].js) {
- feHelper.codeStandardMgr[tabId].allDone = true;
- }
- if (feHelper.codeStandardMgr[tabId].allDone && typeof callback === 'function') {
- callback();
- }
- });
- };
- /**
- * 执行前端FCPHelper检测
- */
- let _doFcpDetect = function (tab) {
- feHelper.codeStandardMgr[tab.id] = feHelper.codeStandardMgr[tab.id] || {};
- //所有元素都准备就绪
- if (feHelper.codeStandardMgr[tab.id].allDone) {
- clearInterval(feHelper.csDetectIntervals[tab.id]);
- chrome.tabs.sendMessage(tab.id, {
- type: MSG_TYPE.CODE_STANDARDS,
- event: MSG_TYPE.FCP_HELPER_DETECT
- });
- } else if (feHelper.csDetectIntervals[tab.id] === undefined) {
- chrome.tabs.sendMessage(tab.id, {
- type: MSG_TYPE.CODE_STANDARDS,
- event: MSG_TYPE.FCP_HELPER_INIT
- });
- //显示桌面提醒
- notifyText({
- message: "正在准备数据,请稍等..."
- });
- feHelper.csDetectIntervals[tab.id] = setInterval(function () {
- _doFcpDetect(tab);
- }, 200);
- }
- };
- /**
- * 文本格式,可以设置一个图标和标题
- * @param {Object} options
- * @config {string} type notification的类型,可选值:html、text
- * @config {string} icon 图标
- * @config {string} title 标题
- * @config {string} message 内容
- */
- let notifyText = function (options) {
- let notifyId = 'fehleper-notify-id';
- clearTimeout(feHelper.notifyTimeoutId);
- if (options.closeImmediately) {
- return chrome.notifications.clear(notifyId);
- }
- if (!options.icon) {
- options.icon = "static/img/fe-48.png";
- }
- if (!options.title) {
- options.title = "温馨提示";
- }
- chrome.notifications.create(notifyId, {
- type: 'basic',
- title: options.title,
- iconUrl: chrome.runtime.getURL(options.icon),
- message: options.message
- });
- feHelper.notifyTimeoutId = setTimeout(() => {
- chrome.notifications.clear(notifyId);
- }, parseInt(options.autoClose || 3000, 10));
- };
- /**
- * 查看页面wpo信息
- */
- let _showPageWpoInfo = function (wpoInfo) {
- chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- if (!wpoInfo) {
- notifyText({
- message: "对不起,检测失败"
- });
- } else {
- chrome.tabs.create({
- url: "wpo/index.html?" + btoa(encodeURIComponent(JSON.stringify(wpoInfo))),
- active: true
- });
- }
- });
- };
- /**
- * 获取页面wpo信息
- * @return {[type]}
- */
- let _getPageWpoInfo = function () {
- chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- let tab = tabs[0];
- //显示桌面提醒
- chrome.tabs.sendMessage(tab.id, {
- type: MSG_TYPE.GET_PAGE_WPO_INFO
- });
- });
- };
- /**
- * 创建或更新成功执行的动作
- * @param evt
- * @param content
- * @private
- */
- let _tabUpdatedCallback = function (evt, content) {
- return function (newTab) {
- if (content) {
- setTimeout(function () {
- chrome.tabs.sendMessage(newTab.id, {
- type: MSG_TYPE.TAB_CREATED_OR_UPDATED,
- content: content,
- event: evt
- });
- }, 300)
- }
- };
- };
- /**
- * 打开对应文件,运行该Helper
- * @param tab
- * @param file
- * @param txt
- * @private
- */
- let _openFileAndRun = function (tab, file, txt) {
- chrome.tabs.query({windowId: chrome.windows.WINDOW_ID_CURRENT}, function (tabs) {
- Settings.getOptsFromBgPage((opts) => {
- let isOpened = false;
- let tabId;
- // 允许在新窗口打开
- if (opts['FORBID_OPEN_IN_NEW_TAB']) {
- let reg = new RegExp("^chrome.*/" + file + "/index.html$", "i");
- for (let i = 0, len = tabs.length; i < len; i++) {
- if (reg.test(tabs[i].url)) {
- isOpened = true;
- tabId = tabs[i].id;
- break;
- }
- }
- }
- if (!isOpened) {
- chrome.tabs.create({
- url: '' + file + '/index.html',
- active: true
- }, _tabUpdatedCallback(file, txt));
- } else {
- chrome.tabs.update(tabId, {highlighted: true}, _tabUpdatedCallback(file, txt));
- }
- });
- });
- };
- /**
- * ajax debugger 开关切换
- * @private
- */
- let _debuggerSwitchOn = function (callback) {
- chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- let tab = tabs[0];
- feHelper.ajaxDebuggerMgr[tab.id] = !feHelper.ajaxDebuggerMgr[tab.id];
- chrome.tabs.executeScript(tab.id, {
- code: 'console.info("FeHelper提醒:Ajax Debugger开关已' + (feHelper.ajaxDebuggerMgr[tab.id] ? '开启' : '关闭') + '!");',
- allFrames: false
- });
- callback && callback();
- });
- };
- /**
- * 告诉DevTools页面,当前的debug开关是否打开
- * @param callback
- * @param withAlert
- * @private
- */
- let _tellDevToolsDbgSwitchOn = function (callback, withAlert) {
- chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- let tab = tabs[0];
- if (tab) {
- callback && callback(feHelper.ajaxDebuggerMgr[tab.id]);
- if (withAlert) {
- let msg = '';
- if (feHelper.ajaxDebuggerMgr[tab.id]) {
- if (devToolsDetected) {
- msg = 'DevTools已打开,确保已切换到【Console】界面,并关注信息输出,愉快的进行Ajax Debugger!'
- } else {
- msg = '请打开DevTools,并切换到【Console】界面,关注信息输出,愉快的进行Ajax Debugger!';
- }
- } else {
- msg = '已停止当前页面的Ajax Debugger功能!';
- }
- alert(msg);
- }
- }
- });
- };
- /**
- * 屏幕栅格标尺
- */
- let _doGridDetect = function (tab) {
- chrome.tabs.sendMessage(tab.id, {
- type: MSG_TYPE.GRID_RULER
- });
- };
- /**
- * 根据给定参数,运行对应的Helper
- */
- let _runHelper = function (config, callback) {
- chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- let tab = tabs[0];
- // 如果是采用独立文件方式访问,直接打开该页面即可
- if (config.useFile === 1) {
- let content = config.msgType === MSG_TYPE.QR_CODE ? tab.url : '';
- _openFileAndRun(tab, config.msgType, content);
- } else {
- switch (config.msgType) {
- //编码规范检测
- case MSG_TYPE.FCP_HELPER_DETECT:
- _doFcpDetect(tab);
- break;
- //将当前网页转为图片
- case MSG_TYPE.PAGE_CAPTURE:
- PageCapture.full(tab);
- break;
- //查看网页加载时间
- case MSG_TYPE.SHOW_PAGE_LOAD_TIME:
- _getPageWpoInfo();
- break;
- //Ajax调试
- case MSG_TYPE.AJAX_DEBUGGER:
- _debuggerSwitchOn(callback);
- break;
- // 屏幕栅格标尺
- case MSG_TYPE.GRID_RULER:
- _doGridDetect(tab);
- break;
- default :
- break;
- }
- }
- });
- };
- /**
- * 检测Google chrome服务能不能访问,在2s内检测心跳
- * @param success
- * @param failure
- */
- let detectGoogleDotCom = function (success, failure) {
- Promise.race([
- fetch('https://clients2.google.com/service/update2/crx'),
- new Promise(function (resolve, reject) {
- setTimeout(() => reject(new Error('request timeout')), 2000)
- })])
- .then((data) => {
- success && success();
- }).catch(() => {
- failure && failure();
- });
- };
- /**
- * 从google官方渠道下载chrome扩展
- * @param crxId 需要下载的extension id
- * @param crxName 扩展名称
- * @param callback 下载动作结束后的回调
- */
- let downloadCrxFileByCrxId = function (crxId, crxName, callback) {
- detectGoogleDotCom(() => {
- // google可以正常访问,则正常下载
- let url = "https://clients2.google.com/service/update2/crx?response=redirect&acceptformat=crx2,crx3&x=id%3D"
- + crxId + "%26uc&prodversion=" + navigator.userAgent.split("Chrome/")[1].split(" ")[0];
- if (!chrome.downloads) {
- let a = document.createElement('a');
- a.href = url;
- a.download = crxName || (crxId + '.crx');
- (document.body || document.documentElement).appendChild(a);
- a.click();
- a.remove();
- } else {
- chrome.downloads.download({
- url: url,
- filename: crxName || crxId,
- conflictAction: 'overwrite',
- saveAs: true
- }, function (downloadId) {
- if (chrome.runtime.lastError) {
- alert('抱歉,下载失败!错误信息:' + chrome.runtime.lastError.message);
- }
- });
- }
- }, () => {
- // google不能正常访问
- callback ? callback() : alert('抱歉,下载失败!');
- });
- };
- /**
- * 从chrome webstore下载crx文件
- * 在chrome extension详情页使用
- */
- let downloadCrxFileFromWebStoreDetailPage = function (callback) {
- chrome.tabs.getSelected(null, function (tab) {
- let crxId = tab.url.split("/")[6].split('?')[0];
- let crxName = tab.title.split(" - Chrome")[0] + ".crx";
- crxName = crxName.replace(/[&\/\\:"*<>|?]/g, '');
- downloadCrxFileByCrxId(crxId, crxName, callback);
- });
- };
- /**
- * 通过右键菜单下载或者分享crx
- * @param tab
- * @private
- */
- let _downloadCrx = function (tab) {
- let isWebStoreDetailPage = tab.url.indexOf('https://chrome.google.com/webstore/detail/') === 0;
- if (isWebStoreDetailPage) {
- // 如果是某个chrome extension的详情页面了,直接下载当前crx文件
- downloadCrxFileFromWebStoreDetailPage(() => {
- alert('下载失败,可能是当前网络无法访问Google站点!');
- });
- } else {
- // 否则,下载FeHelper并分享出去:ID:pkgccpejnmalmdinmhkkfafefagiiiad
- // feHelper.manifest.name
- if (confirm('下载最新版【FeHelper】并分享给其他小伙伴儿,走你~~~')) {
- let crxId = MSG_TYPE.STABLE_EXTENSION_ID;
- let crxName = feHelper.manifest.name + '- latestVersion.crx';
- downloadCrxFileByCrxId(crxId, crxName, () => {
- chrome.tabs.create({
- url: MSG_TYPE.DOWNLOAD_FROM_GITHUB
- });
- });
- }
- }
- };
- /**
- * 右键菜单创建工具
- * @param menuList
- * @private
- */
- let _contextMenuCreator = function (menuList) {
- let menus = Settings.getMenuOpts();
- menuList.forEach(m => {
- if (m === 'MENU_PAGE_ENCODING') {
- // 网页编码设置的menu
- PageEncoding.createMenu(feHelper.contextMenuId, menus.MENU_PAGE_ENCODING);
- } else {
- let onClick = {
- MENU_QRCODE_CREATE: function (info, tab) {
- chrome.tabs.executeScript(tab.id, {
- code: '(' + (function (pInfo) {
- let linkUrl = pInfo.linkUrl;
- let pageUrl = pInfo.pageUrl;
- let imgUrl = pInfo.srcUrl;
- let selection = pInfo.selectionText;
- return linkUrl || imgUrl || selection || pageUrl;
- }).toString() + ')(' + JSON.stringify(info) + ')',
- allFrames: false
- }, function (txt) {
- _openFileAndRun(tab, MSG_TYPE.QR_CODE, (typeof txt === 'object') ? txt[0] : txt);
- });
- },
- MENU_QRCODE_DECODE: function (info, tab) {
- _qrDecode(info, tab);
- },
- MENU_PAGE_CAPTURE: function (info, tab) {
- PageCapture.full(tab);
- },
- MENU_COLOR_PICKER: function (info, tab) {
- _showColorPicker();
- },
- MENU_STR_ENDECODE: function (info, tab) {
- chrome.tabs.executeScript(tab.id, {
- code: '(' + (function (pInfo) {
- return pInfo.selectionText;
- }).toString() + ')(' + JSON.stringify(info) + ')',
- allFrames: false
- }, function (txt) {
- _openFileAndRun(tab, MSG_TYPE.EN_DECODE, (typeof txt === 'object') ? txt[0] : txt);
- });
- },
- MENU_JSON_FORMAT: function (info, tab) {
- chrome.tabs.executeScript(tab.id, {
- code: '(' + (function (pInfo) {
- return pInfo.selectionText;
- }).toString() + ')(' + JSON.stringify(info) + ')',
- allFrames: false
- }, function (txt) {
- _openFileAndRun(tab, MSG_TYPE.JSON_FORMAT, (typeof txt === 'object') ? txt[0] : txt);
- });
- },
- MENU_CODE_FORMAT: function (info, tab) {
- chrome.tabs.executeScript(tab.id, {
- code: '(' + (function (pInfo) {
- return pInfo.selectionText;
- }).toString() + ')(' + JSON.stringify(info) + ')',
- allFrames: false
- }, function (txt) {
- _openFileAndRun(tab, MSG_TYPE.CODE_BEAUTIFY, (typeof txt === 'object') ? txt[0] : txt);
- });
- },
- MENU_AJAX_DEBUGGER: function (info, tab) {
- _debuggerSwitchOn(() => {
- _tellDevToolsDbgSwitchOn(null, true);
- });
- },
- MENU_CODE_STANDARD: function (info, tab) {
- _doFcpDetect(tab);
- },
- MENU_PAGE_OPTIMI: function (info, tab) {
- _getPageWpoInfo();
- },
- MENU_IMAGE_BASE64: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.IMAGE_BASE64, info.srcUrl);
- },
- MENU_JSON_COMPARE: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.JSON_COMPARE);
- },
- MENU_CODE_COMPRESS: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.CODE_COMPRESS);
- },
- MENU_TIME_STAMP: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.TIME_STAMP);
- },
- MENU_RANDOM_PASS: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.RANDOM_PASSWORD);
- },
- MENU_JS_REGEXP: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.REGEXP_TOOL);
- },
- MENU_MARKDOWN_TL: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.HTML_TO_MARKDOWN);
- },
- MENU_STICKY_NOTE: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.STICKY_NOTES);
- },
- MENU_REMOVE_BG: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.REMOVE_BG);
- },
- MENU_MULTI_TOOLKIT: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.MULTI_TOOLKIT);
- },
- MENU_PAGE_MODIFIER: function (info, tab) {
- _openFileAndRun(tab, MSG_TYPE.PAGE_MODIFIER);
- },
- MENU_GRID_RULER: function (info, tab) {
- _doGridDetect(tab);
- },
- MENU_DOWNLOAD_CRX: function (info, tab) {
- _downloadCrx(tab);
- }
- };
- chrome.contextMenus.create({
- title: menus[m].icon + ' ' + menus[m].text,
- contexts: menus[m].contexts || ['all'],
- parentId: feHelper.contextMenuId,
- onclick: onClick[m]
- });
- }
- });
- };
- /**
- * 创建扩展专属的右键菜单
- */
- let _createContextMenu = function () {
- _removeContextMenu();
- feHelper.contextMenuId = chrome.contextMenus.create({
- title: "FeHelper工具",
- contexts: ['page', 'selection', 'editable', 'link', 'image'],
- documentUrlPatterns: ['http://*/*', 'https://*/*', 'file://*/*']
- });
- if (!Settings.didMenuSettingSaved()) {
- _contextMenuCreator(Settings.getDefaultContextMenus());
- } else {
- Settings.getOptsFromBgPage((opts) => {
- _contextMenuCreator(Object.keys(opts).filter(m => /^MENU_/.test(m)));
- });
- }
- };
- /**
- * 移除扩展专属的右键菜单
- */
- let _removeContextMenu = function () {
- if (!feHelper.contextMenuId) return;
- chrome.contextMenus.remove(feHelper.contextMenuId);
- feHelper.contextMenuId = null;
- };
- /**
- * 创建或移除扩展专属的右键菜单
- */
- let _createOrRemoveContextMenu = function () {
- Settings.getOptsFromBgPage((opts) => {
- if (opts['opt_item_contextMenus']) {
- _createContextMenu();
- } else {
- _removeContextMenu();
- }
- });
- };
- /**
- * 二维码转码
- * @param info
- * @param tab
- * @private
- */
- let _qrDecode = function (info, tab) {
- let qrcode = Tarp.require('../static/vendor/zxing/zxing.min.js');
- qrcode.callback = function (text) {
- if ((text || '').indexOf('error decoding QR Code') !== -1) {
- let image = new Image();
- image.src = info.srcUrl;
- image.onload = function () {
- let width = this.naturalWidth;
- let height = this.naturalHeight;
- // url方式解码失败,再转换成data uri后继续解码
- (function createCanvasContext(img, t, l, w, h) {
- let canvas = document.createElement('canvas');
- canvas.setAttribute('id', 'qr-canvas');
- canvas.height = h + 100;
- canvas.width = w + 100;
- let context = canvas.getContext('2d');
- context.fillStyle = 'rgb(255,255,255)';
- context.fillRect(0, 0, canvas.width, canvas.height);
- context.drawImage(img, l, t, w, h, 50, 50, w, h);
- qrcode.callback = function (txt) {
- chrome.tabs.sendMessage(tab.id, {
- type: MSG_TYPE.QR_DECODE,
- result: txt
- });
- };
- qrcode.decode(canvas.toDataURL());
- })(image, 0, 0, width, height);
- }
- } else {
- chrome.tabs.sendMessage(tab.id, {
- type: MSG_TYPE.QR_DECODE,
- result: text
- });
- }
- };
- qrcode.decode(info.srcUrl);
- };
- /**
- * 显示color picker
- * @private
- */
- let _showColorPicker = function () {
- chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- let tab = tabs[0];
- let tabid = tab.id;
- chrome.tabs.sendMessage(tabid, {
- type: MSG_TYPE.SHOW_COLOR_PICKER,
- enableColorPicker: true
- }, function (response) {
- chrome.tabs.sendMessage(tabid, {
- type: MSG_TYPE.SHOW_COLOR_PICKER,
- doPick: true
- }, function (r) {
- });
- });
- });
- };
- /**
- * 将网页截成一张图,实现取色
- * @param callback
- * @private
- */
- let _drawColorPicker = function (callback) {
- chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- let tab = tabs[0];
- let tabid = tab.id;
- chrome.tabs.captureVisibleTab(null, {format: 'png'}, function (dataUrl) {
- chrome.tabs.sendMessage(tabid, {
- type: MSG_TYPE.SHOW_COLOR_PICKER,
- setPickerImage: true,
- pickerImage: dataUrl
- }, function (response) {
- callback && callback();
- });
- });
- });
- };
- /**
- * 在当前页面的控制台输出console
- * @param request
- * @private
- */
- let _ajaxDebugger = function (request) {
- chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- let tab = tabs[0];
- chrome.tabs.executeScript(tab.id, {
- code: "(" + (function (jsonStr) {
- let args = JSON.parse(unescape(jsonStr));
- console[args[0]].apply(console, Array.prototype.slice.call(args, 1));
- }).toString() + ")('" + request.content + "');"
- });
- });
- };
- //判断是否可以针对json页面进行自动格式化
- let _jsonAutoFormatRequest = function () {
- Settings.getOptsFromBgPage(opts => {
- opts.JSON_PAGE_FORMAT && chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- chrome.tabs.sendMessage(tabs[0].id, {
- type: MSG_TYPE.JSON_PAGE_FORMAT,
- options: {
- MAX_JSON_KEYS_NUMBER: opts.MAX_JSON_KEYS_NUMBER,
- AUTO_TEXT_DECODE: opts.AUTO_TEXT_DECODE === 'true'
- }
- });
- });
- });
- };
- //判断是否可以针对js、css自动检测格式化
- let _jsCssAutoDetectRequest = function () {
- chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
- let tab = tabs[0];
- chrome.tabs.executeScript(tab.id, {
- code: '(' + (() => {
- let ext = location.pathname.substring(location.pathname.lastIndexOf(".") + 1).toLowerCase();
- let fileType = ({'js': 'javascript', 'css': 'css'})[ext];
- let contentType = document.contentType.toLowerCase();
- if (!fileType) {
- if (/\/javascript$/.test(contentType)) {
- fileType = 'javascript';
- } else if (/\/css$/.test(contentType)) {
- fileType = 'css';
- }
- } else if (contentType === 'text/html') {
- fileType = undefined;
- }
- return fileType;
- }).toString() + ')()'
- }, function (fileType) {
- if (fileType && fileType.length && (fileType[0] === 'javascript' || fileType[0] === 'css')) {
- Settings.getOptsFromBgPage(opts => {
- opts.JS_CSS_PAGE_BEAUTIFY && chrome.tabs.sendMessage(tab.id, {
- type: MSG_TYPE.JS_CSS_PAGE_BEAUTIFY,
- content: fileType[0]
- });
- });
- }
- });
- });
- };
- /**
- * 存储 网页涂鸦精灵 的配置
- * @param params
- * @param callback
- * @private
- */
- let _savePageModifierConfigs = function (params, callback) {
- !RegExp.prototype.toJSON && Object.defineProperty(RegExp.prototype, "toJSON", {
- value: RegExp.prototype.toString
- });
- localStorage.setItem(MSG_TYPE.PAGE_MODIFIER_KEY, JSON.stringify(params));
- callback && callback();
- };
- /**
- * 获取 网页涂鸦精灵 的配置,如果指定了url参数,则表示只获取对应的一条配置,否则获取全部
- * @param params
- * @param callback
- * @returns {*}
- * @private
- */
- let _getPageModifierConfigs = function (params, callback) {
- let cacheModifiers = JSON.parse(localStorage.getItem(MSG_TYPE.PAGE_MODIFIER_KEY) || '[]');
- if (params && params.url) {
- let result = null;
- cacheModifiers.some(cm => {
- let m = cm.mPattern.match(/\/(.*)\/(.*)?/);
- if ((new RegExp(m[1], m[2] || "")).test(params.url)) {
- result = cm;
- return true;
- }
- return false;
- });
- callback && callback(result);
- } else {
- callback && callback(cacheModifiers);
- }
- };
- /**
- * 接收来自content_scripts发来的消息
- */
- let _addExtensionListener = function () {
- chrome.runtime.onMessage.addListener(function (request, sender, callback) {
- //提取配置项
- if (request.type === MSG_TYPE.GET_OPTIONS) {
- Settings.getOptsFromBgPage(callback);
- }
- //保存配置项
- else if (request.type === MSG_TYPE.SET_OPTIONS) {
- Settings.setOptsFromBgPage(request.items);
- //管理右键菜单
- _createOrRemoveContextMenu();
- notifyText({
- message: '配置已生效,请继续使用!',
- autoClose: 2000
- });
- }
- // 判断菜单是否保存过
- else if (request.type === MSG_TYPE.MENU_SAVED) {
- Settings.didMenuSettingSaved(callback);
- }
- //判断是否可以针对json页面进行自动格式化
- else if (request.type === MSG_TYPE.JSON_PAGE_FORMAT_REQUEST) {
- _jsonAutoFormatRequest();
- }
- //判断是否可以针对js、css自动检测格式化
- else if (request.type === MSG_TYPE.JS_CSS_PAGE_BEAUTIFY_REQUEST) {
- _jsCssAutoDetectRequest();
- }
- //保存当前网页加载时间
- else if (request.type === MSG_TYPE.CALC_PAGE_LOAD_TIME) {
- _showPageWpoInfo(request.wpo);
- }
- // color picker
- else if (request.type === MSG_TYPE.COLOR_PICKER) {
- _drawColorPicker(callback);
- }
- // console switch
- else if (request.type === MSG_TYPE.AJAX_DEBUGGER_SWITCH) {
- _tellDevToolsDbgSwitchOn(callback);
- }
- // console show
- else if (request.type === MSG_TYPE.AJAX_DEBUGGER_CONSOLE) {
- _ajaxDebugger(request);
- }
- // 打开设置页
- else if (request.type === MSG_TYPE.OPEN_OPTIONS_PAGE) {
- chrome.runtime.openOptionsPage();
- }
- // 开启remove-bg功能
- else if (request.type === MSG_TYPE.REMOVE_PERSON_IMG_BG) {
- Tarp.require('../remove-bg/proxy').addBackgroundRemoveListener(callback);
- }
- // 网页涂鸦精灵:获取配置
- else if (request.type === MSG_TYPE.GET_PAGE_MODIFIER_CONFIG) {
- _getPageModifierConfigs(request.params, callback);
- }
- // 网页涂鸦精灵:保存配置
- else if (request.type === MSG_TYPE.SAVE_PAGE_MODIFIER_CONFIG) {
- _savePageModifierConfigs(request.params, callback);
- }
- // ===========================以下为编码规范检测====start==================================
- //处理CSS的请求
- else if (request.type === MSG_TYPE.GET_CSS) {
- //直接AJAX获取CSS文件内容
- Network.readFileContent(request.link, callback);
- }
- //处理JS的请求
- else if (request.type === MSG_TYPE.GET_JS) {
- //直接AJAX获取JS文件内容
- Network.readFileContent(request.link, callback);
- }
- //处理HTML的请求
- else if (request.type === MSG_TYPE.GET_HTML) {
- //直接AJAX获取JS文件内容
- Network.readFileContent(request.link, callback);
- }
- //处理cookie
- else if (request.type === MSG_TYPE.GET_COOKIE) {
- Network.getCookies(request, callback);
- }
- //移除cookie
- else if (request.type === MSG_TYPE.REMOVE_COOKIE) {
- Network.removeCookie(request, callback);
- }
- //设置cookie
- else if (request.type === MSG_TYPE.SET_COOKIE) {
- Network.setCookie(request, callback);
- }
- //CSS准备就绪
- else if (request.type === MSG_TYPE.CSS_READY) {
- _detectReadyState('css', callback);
- }
- //JS准备就绪
- else if (request.type === MSG_TYPE.JS_READY) {
- _detectReadyState('js', callback);
- }
- //HTML准备就绪
- else if (request.type === MSG_TYPE.HTML_READY) {
- _detectReadyState('html', callback);
- }
- // ===========================以上为编码规范检测====end==================================
- return true;
- });
- // 检测DevTools是否打开
- let openCount = 0;
- chrome.runtime.onConnect.addListener(function (port) {
- if (port.name === MSG_TYPE.DEV_TOOLS) {
- if (openCount === 0) {
- devToolsDetected = true;
- }
- openCount++;
- port.onDisconnect.addListener(function (port) {
- openCount--;
- if (openCount === 0) {
- devToolsDetected = false;
- }
- });
- }
- });
- // 安装与更新
- chrome.runtime.onInstalled.addListener(({reason, previousVersion}) => {
- switch (reason) {
- case 'install':
- chrome.runtime.openOptionsPage();
- break;
- case 'update':
- setTimeout(() => {
- chrome.browserAction.setBadgeText({text: '+++1'});
- setTimeout(() => {
- chrome.browserAction.setBadgeText({text: ''});
- }, 1500);
- }, 1500);
- break;
- }
- });
- // 卸载
- chrome.runtime.setUninstallURL(feHelper.manifest.homepage_url);
- };
- /**
- * 检查插件更新
- * @private
- */
- let _checkUpdate = function () {
- setTimeout(() => {
- chrome.runtime.requestUpdateCheck((status) => {
- if (status === "update_available") {
- chrome.runtime.reload();
- }
- });
- }, 1000 * 10);
- };
- /**
- * 初始化
- */
- let _init = function () {
- _checkUpdate();
- _addExtensionListener();
- _createOrRemoveContextMenu();
- };
- /**
- * 打开任意一个URL
- * @param url
- * @private
- */
- let _openUrl = function(url){
- chrome.tabs.create({url: url});
- };
- return {
- init: _init,
- runHelper: _runHelper,
- notify: notifyText,
- showColorPicker: _showColorPicker,
- tellMeAjaxDbgSwitch: _tellDevToolsDbgSwitchOn,
- getCapturedData: PageCapture.getCapturedData,
- openUrl: _openUrl
- };
- })();
- //初始化
- BgPageInstance.init();
|