瀏覽代碼

整体功能回归

[email protected] 2 年之前
父節點
當前提交
d95e31c427

+ 13 - 67
apps/background/background.js

@@ -8,6 +8,8 @@ import MSG_TYPE from '../static/js/common.js';
 import Settings from '../options/settings.js';
 import Menu from './menu.js';
 import Awesome from './awesome.js';
+import InjectTools from './inject-tools.js';
+import Monkey from './monkey.js';
 
 
 let BgPageInstance = (function () {
@@ -56,66 +58,7 @@ let BgPageInstance = (function () {
 
     };
 
-    /**
-     * 如果tabId指定的tab还存在,就正常注入脚本
-     * @param tabId 需要注入脚本的tabId
-     * @param codeConfig 需要注入的代码
-     * @param callback 注入代码后的callback
-     */
-    let injectScriptIfTabExists = function (tabId, codeConfig, callback) {
-        chrome.tabs.query({currentWindow: true}, (tabs) => {
-            tabs.some(tab => {
-                if (tab.id !== tabId) return false;
-                Settings.getOptions((opts) => {
-
-                    if (!codeConfig.hasOwnProperty('allFrames')) {
-                        codeConfig.allFrames = String(opts['CONTENT_SCRIPT_ALLOW_ALL_FRAMES']) === 'true';
-                    }
 
-                    codeConfig.code = 'try{' + codeConfig.code + ';}catch(e){};';
-                    // 有文件就注入文件
-                    if(codeConfig.files && codeConfig.files.length){
-                        // 注入样式
-                        if(codeConfig.files.join(',').indexOf('.css') > -1) {
-                            chrome.scripting.insertCSS({
-                                target: {tabId, allFrames: codeConfig.allFrames},
-                                files: codeConfig.files
-                            }, function () {
-                                callback && callback.apply(this, arguments);
-                            });
-                        }
-                        // 注入js
-                        else {
-                            chrome.scripting.executeScript({
-                                target: {tabId, allFrames: codeConfig.allFrames},
-                                files: codeConfig.files
-                            }, function () {
-                                chrome.scripting.executeScript({
-                                    target: {tabId, allFrames: codeConfig.allFrames},
-                                    func: function(code){evalCore.getEvalInstance(window)(code)},
-                                    args: [codeConfig.code]
-                                }, function () {
-                                    callback && callback.apply(this, arguments);
-                                });
-                            });
-                        }
-                    }else{
-                        // 没有文件就只注入脚本
-                        chrome.scripting.executeScript({
-                            target: {tabId, allFrames: codeConfig.allFrames},
-                            func: function(code){evalCore.getEvalInstance(window)(code)},
-                            args: [codeConfig.code]
-                        }, function () {
-                            callback && callback.apply(this, arguments);
-                        });
-                    }
-
-                });
-
-                return true;
-            });
-        });
-    };
 
     // 往当前页面直接注入脚本,不再使用content-script的配置了
     let _injectContentScripts = function (tabId) {
@@ -126,7 +69,7 @@ let BgPageInstance = (function () {
             // 注入样式
             let cssFiles = Object.keys(tools).filter(tool => tools[tool].contentScriptCss)
                             .map(tool => `${tool}/content-script.css`);
-            injectScriptIfTabExists(tabId, {files: cssFiles});
+            InjectTools.inject(tabId, {files: cssFiles});
 
             // 注入js
             let jsTools = Object.keys(tools).filter(tool => tools[tool].contentScriptJs);
@@ -136,7 +79,7 @@ let BgPageInstance = (function () {
                 jsCodes.push(`(()=>{let func=${func};func&&func();})()`);
             });
             let jsFiles = jsTools.map(tool => `${tool}/content-script.js`);
-            injectScriptIfTabExists(tabId, {files: jsFiles,code: jsCodes.join(';')});
+            InjectTools.inject(tabId, {files: jsFiles,code: jsCodes.join(';')});
         });
     };
 
@@ -163,7 +106,7 @@ let BgPageInstance = (function () {
                 let found = tabs.some(tab => {
                     if (/^(http(s)?|file):\/\//.test(tab.url) && blacklist.every(reg => !reg.test(tab.url))) {
                         let codes = `window['${toolFunc}NoPage'] && window['${toolFunc}NoPage'](${JSON.stringify(tab)});`;
-                        injectScriptIfTabExists(tab.id, {code: codes});
+                        InjectTools.inject(tab.id, {code: codes});
                         return true;
                     }
                     return false;
@@ -361,11 +304,11 @@ let BgPageInstance = (function () {
     let _addScreenShotByPages = function(params){
         chrome.tabs.captureVisibleTab(null, {format: 'png', quality: 100}, uri => {
             let code = `window.addScreenShot(${JSON.stringify(params)},'${uri}');`
-            injectScriptIfTabExists(params.tabInfo.id, { code });
+            InjectTools.inject(params.tabInfo.id, { code });
         });
 
         let code = `window.addScreenShot(${JSON.stringify(params)},'${uri}');`
-        injectScriptIfTabExists(params.tabInfo.id, { code: `window.captureCallback();` });
+        InjectTools.inject(params.tabInfo.id, { code: `window.captureCallback();` });
     };
 
     let _colorPickerCapture = function(params) {
@@ -375,7 +318,7 @@ let BgPageInstance = (function () {
                     setPickerImage: true,
                     pickerImage: dataUrl
                 })})`;
-                injectScriptIfTabExists(tabs[0].id, { code });
+                InjectTools.inject(tabs[0].id, { code });
             });
         });
     };
@@ -385,7 +328,7 @@ let BgPageInstance = (function () {
             Awesome.StorageMgr.get('JS_CSS_PAGE_BEAUTIFY').then(val => {
                 if(val !== '0') {
                     let code = `window._codebutifydetect_('${params.fileType}')`;
-                    injectScriptIfTabExists(params.tabId, { code });
+                    InjectTools.inject(params.tabId, { code });
                 }
             });
         }
@@ -467,6 +410,9 @@ let BgPageInstance = (function () {
                     case 'add-screen-shot-by-pages':
                         _addScreenShotByPages(request.params);
                         break;
+                    case 'request-monkey-start':
+                        Monkey.start(request.params);
+                        break;
                 }
                 callback && callback(request.params);
             } else {
@@ -483,7 +429,7 @@ let BgPageInstance = (function () {
             if (String(changeInfo.status).toLowerCase() === "complete") {
 
                 if(/^(http(s)?|file):\/\//.test(tab.url) && blacklist.every(reg => !reg.test(tab.url))){
-                    injectScriptIfTabExists(tabId, { code: `window.__FH_TAB_ID__=${tabId};` });
+                    InjectTools.inject(tabId, { code: `window.__FH_TAB_ID__=${tabId};` });
                     _injectContentScripts(tabId);
                 }
             }

+ 66 - 0
apps/background/inject-tools.js

@@ -0,0 +1,66 @@
+import Settings from '../options/settings.js';
+
+export default (() => {
+    /**
+     * 如果tabId指定的tab还存在,就正常注入脚本
+     * @param tabId 需要注入脚本的tabId
+     * @param codeConfig 需要注入的代码
+     * @param callback 注入代码后的callback
+     */
+    let injectScriptIfTabExists = function (tabId, codeConfig, callback) {
+        chrome.tabs.query({currentWindow: true}, (tabs) => {
+            tabs.some(tab => {
+                if (tab.id !== tabId) return false;
+                Settings.getOptions((opts) => {
+
+                    if (!codeConfig.hasOwnProperty('allFrames')) {
+                        codeConfig.allFrames = String(opts['CONTENT_SCRIPT_ALLOW_ALL_FRAMES']) === 'true';
+                    }
+
+                    codeConfig.code = 'try{' + codeConfig.code + ';}catch(e){};';
+                    // 有文件就注入文件
+                    if(codeConfig.files && codeConfig.files.length){
+                        // 注入样式
+                        if(codeConfig.files.join(',').indexOf('.css') > -1) {
+                            chrome.scripting.insertCSS({
+                                target: {tabId, allFrames: codeConfig.allFrames},
+                                files: codeConfig.files
+                            }, function () {
+                                callback && callback.apply(this, arguments);
+                            });
+                        }
+                        // 注入js
+                        else {
+                            chrome.scripting.executeScript({
+                                target: {tabId, allFrames: codeConfig.allFrames},
+                                files: codeConfig.files
+                            }, function () {
+                                chrome.scripting.executeScript({
+                                    target: {tabId, allFrames: codeConfig.allFrames},
+                                    func: function(code){evalCore.getEvalInstance(window)(code)},
+                                    args: [codeConfig.code]
+                                }, function () {
+                                    callback && callback.apply(this, arguments);
+                                });
+                            });
+                        }
+                    }else{
+                        // 没有文件就只注入脚本
+                        chrome.scripting.executeScript({
+                            target: {tabId, allFrames: codeConfig.allFrames},
+                            func: function(code){evalCore.getEvalInstance(window)(code)},
+                            args: [codeConfig.code]
+                        }, function () {
+                            callback && callback.apply(this, arguments);
+                        });
+                    }
+
+                });
+
+                return true;
+            });
+        });
+    };
+
+    return { inject: injectScriptIfTabExists };
+})();

+ 100 - 0
apps/background/monkey.js

@@ -0,0 +1,100 @@
+
+import InjectTools from './inject-tools.js';
+
+export default (() => {
+    let start = (params) => {
+        try {
+            const PAGE_MONKEY_LOCAL_STORAGE_KEY = 'PAGE-MODIFIER-LOCAL-STORAGE-KEY';
+
+            let handler = monkeys => {
+                monkeys.filter(cm => !cm.mDisabled).forEach(cm => {
+                    let result = null;
+                    let matched = cm.mPattern.match(/^\/(.*)\/(.*)?$/);
+                    if (matched && ( !matched[2] || matched[2] && !/[^igm]*/i.test(matched[2]))) {
+                        // 正则,直接匹配
+                        cm.mPattern = new RegExp(matched[1], matched[2] || "");
+                        result = cm.mPattern.test(params.url) && cm;
+                    } else if (cm.mPattern.indexOf('*') > -1) {
+                        if (cm.mPattern.startsWith('*://')) {
+                            cm.mPattern = cm.mPattern.replace('*://', '(http|https|file)://');
+                        } else if (cm.mPattern.indexOf('://') < 0) {
+                            cm.mPattern = '(http|https|file)://' + cm.mPattern;
+                        }
+
+                        // 通配符,则转换为正则再匹配
+                        cm.mPattern = new RegExp('^' + cm.mPattern.replace(/\./g,'\\.').replace(/\//g, '\\/').replace(/\*/g, '.*').replace(/\?/g, '\\?') + '$');
+                        result = cm.mPattern.test(params.url) && cm;
+                    } else {
+                        // 绝对地址,直接比对
+                        let arr = [cm.mPattern, `${cm.mPattern}/`];
+                        if (!cm.mPattern.startsWith('http://') && !cm.mPattern.startsWith('https://')) {
+                            arr = arr.concat([`http://${cm.mPattern}`, `http://${cm.mPattern}/`,
+                                `https://${cm.mPattern}`, `https://${cm.mPattern}/`]);
+                        }
+                        if (arr.includes(params.url)) {
+                            result = cm;
+                        }
+                    }
+
+                    if (result) {
+                        let scripts = '(' + ((monkey) => {
+                            let injectFunc = () => {
+                                // 执行脚本
+                                evalCore.getEvalInstance(window)(monkey.mScript);
+
+                                parseInt(monkey.mRefresh) && setTimeout(() => {
+                                    location.reload(true);
+                                }, parseInt(monkey.mRefresh) * 1000);
+                            };
+
+                            window._fhImportJs = js => {
+                                return fetch(js).then(resp => resp.text()).then(jsText => {
+                                    if(window.evalCore && window.evalCore.getEvalInstance){
+                                         return window.evalCore.getEvalInstance(window)(jsText);
+                                    }
+                                    let el = document.createElement('script');
+                                    el.textContent = jsText;
+                                    document.head.appendChild(el);
+                                });
+                            };
+
+                            let jsFiles = (monkey.mRequireJs || '').split(/[\s,,]+/).filter(js => js.length);
+                            if (jsFiles.length) {
+                                let arrPromise = Array.from(new Set(jsFiles)).map(js => window._fhImportJs(js));
+                                Promise.all(arrPromise).then(injectFunc);
+                            } else {
+                                injectFunc();
+                            }
+                        }).toString() + `)(${JSON.stringify(result)})`;
+                        InjectTools.inject(params.tabId, {code: scripts, allFrames: false});
+                    }
+                });
+            };
+
+            chrome.storage.local.get(PAGE_MONKEY_LOCAL_STORAGE_KEY, (resps) => {
+                let cacheMonkeys, storageMode = false;
+                if (!resps || !resps[PAGE_MONKEY_LOCAL_STORAGE_KEY]) {
+                    cacheMonkeys = localStorage.getItem(PAGE_MONKEY_LOCAL_STORAGE_KEY) || '[]';
+                    storageMode = true;
+                } else {
+                    cacheMonkeys = resps[PAGE_MONKEY_LOCAL_STORAGE_KEY] || '[]';
+                }
+
+                params && params.url && handler(JSON.parse(cacheMonkeys));
+
+                // 本地存储的内容,需要全部迁移到chrome.storage.local中,以确保unlimitedStorage
+                if (storageMode) {
+                    let storageData = {};
+                    storageData[PAGE_MONKEY_LOCAL_STORAGE_KEY] = cacheMonkeys;
+                    chrome.storage.local.set(storageData);
+                }
+            });
+
+        } catch (e) {
+            console.log('monkey error',e);
+        }
+        return true;
+    };
+
+    return {start};
+})();

+ 1 - 1
apps/code-beautify/index.js

@@ -20,7 +20,7 @@ new Vue({
                     thing: 'request-page-content',
                     tabId: activeTab.id
                 }).then(resp => {
-                    if(!resp && !resp.content) return ;
+                    if(!resp || !resp.content) return ;
                     this.sourceContent = resp.content;
                     this.format();
                 });

+ 1 - 1
apps/en-decode/index.js

@@ -23,7 +23,7 @@ new Vue({
                     thing: 'request-page-content',
                     tabId: activeTab.id
                 }).then(resp => {
-                    if(!resp && !resp.content) return ;
+                    if(!resp || !resp.content) return ;
                     this.sourceContent = resp.content;
                     this.convert();
                 });

+ 0 - 1
apps/html2markdown/index.html

@@ -7,7 +7,6 @@
     <link rel="stylesheet" href="index.css" />
     <script type="text/javascript" src="../static/vendor/evalCore.min.js"></script>
     <script type="text/javascript" src="../static/vendor/vue/vue.js"></script>
-    <script src="../static/vendor/require/require.js"></script>
 </head>
 <body>
 

+ 1 - 1
apps/image-base64/index.js

@@ -43,7 +43,7 @@ new Vue({
                     thing: 'request-page-content',
                     tabId: activeTab.id
                 }).then(resp => {
-                    if(!resp && !resp.content) return ;
+                    if(!resp || !resp.content) return ;
                     if (this.curType !== 'image') {
                         this.trans();
                     }

+ 1 - 1
apps/json-format/index.js

@@ -70,7 +70,7 @@ new Vue({
                     tabId: activeTab.id
                 }).then(resp => {
                     if(!resp && !resp.content) return ;
-                    editor.setValue(resp.content || this.defaultResultTpl);
+                    editor.setValue(resp.content || '');
                     this.format();
                 });
             });

+ 3 - 1
apps/loan-rate/index.js

@@ -22,6 +22,7 @@ new Vue({
         },
 
         revRate: 0,
+        revMoney: 10000,
         revAllAmount: 11347.20,
         revAllInterest: 0
     },
@@ -312,8 +313,9 @@ new Vue({
                 return result;
             };
 
+            this.money = this.revMoney;
             this.revAllInterest = Math.round((this.revAllAmount - this.money) * 100) / 100;
             this.revRate = guessRate(this.money, this.months, this.revAllAmount, parseInt(this.paybackMode));
         }
     }
-});
+});

+ 3 - 99
apps/page-monkey/content-script.js

@@ -4,106 +4,10 @@
 window.pagemonkeyContentScript = function () {
     chrome.runtime.sendMessage({
         type: 'fh-dynamic-any-thing',
+        thing: 'request-monkey-start',
         params: {
             url: location.href,
             tabId: window.__FH_TAB_ID__
-        },
-        func: ((params, callback) => {
-            try {
-                const PAGE_MONKEY_LOCAL_STORAGE_KEY = 'PAGE-MODIFIER-LOCAL-STORAGE-KEY';
-
-                let handler = monkeys => {
-                    monkeys.filter(cm => !cm.mDisabled).forEach(cm => {
-                        let result = null;
-                        let matched = cm.mPattern.match(/^\/(.*)\/(.*)?$/);
-                        if (matched && ( !matched[2] || matched[2] && !/[^igm]*/i.test(matched[2]))) {
-                            // 正则,直接匹配
-                            cm.mPattern = new RegExp(matched[1], matched[2] || "");
-                            result = cm.mPattern.test(params.url) && cm;
-                        } else if (cm.mPattern.indexOf('*') > -1) {
-                            if (cm.mPattern.startsWith('*://')) {
-                                cm.mPattern = cm.mPattern.replace('*://', '(http|https|file)://');
-                            } else if (cm.mPattern.indexOf('://') < 0) {
-                                cm.mPattern = '(http|https|file)://' + cm.mPattern;
-                            }
-
-                            // 通配符,则转换为正则再匹配
-                            cm.mPattern = new RegExp('^' + cm.mPattern.replace(/\./g,'\\.').replace(/\//g, '\\/').replace(/\*/g, '.*').replace(/\?/g, '\\?') + '$');
-                            result = cm.mPattern.test(params.url) && cm;
-                        } else {
-                            // 绝对地址,直接比对
-                            let arr = [cm.mPattern, `${cm.mPattern}/`];
-                            if (!cm.mPattern.startsWith('http://') && !cm.mPattern.startsWith('https://')) {
-                                arr = arr.concat([`http://${cm.mPattern}`, `http://${cm.mPattern}/`,
-                                    `https://${cm.mPattern}`, `https://${cm.mPattern}/`]);
-                            }
-                            if (arr.includes(params.url)) {
-                                result = cm;
-                            }
-                        }
-
-                        if (result) {
-                            let scripts = '(' + ((monkey) => {
-                                let injectFunc = () => {
-                                    let el = document.createElement('script');
-                                    el.type = 'text/javascript';
-                                    el.textContent = monkey.mScript;
-                                    document.body.appendChild(el);
-                                    parseInt(monkey.mRefresh) && setTimeout(() => {
-                                        location.reload(true);
-                                    }, parseInt(monkey.mRefresh) * 1000);
-                                };
-
-                                window._fhImportJs = js => {
-                                    return new Promise(resolve => {
-                                        let e = document.createElement('script');
-                                        e.type = 'text/javascript';
-                                        e.src = js;
-                                        e.addEventListener('load', resolve, false);
-                                        document.body.appendChild(e);
-                                    });
-                                };
-
-                                let jsFiles = (monkey.mRequireJs || '').split(/[\s,,]+/).filter(js => js.length);
-                                if (jsFiles.length) {
-                                    let arrPromise = Array.from(new Set(jsFiles)).map(js => window._fhImportJs(js));
-                                    Promise.all(arrPromise).then(injectFunc);
-                                } else {
-                                    injectFunc();
-                                }
-                            }).toString() + `)(${JSON.stringify(result)})`;
-                            if (typeof injectScriptIfTabExists === 'function') {
-                                injectScriptIfTabExists(params.tabId, {code: scripts, allFrames: false});
-                            } else {
-                                chrome.tabs.executeScript(params.tabId, {code: scripts, allFrames: false});
-                            }
-                        }
-                    });
-                };
-
-                chrome.storage.local.get(PAGE_MONKEY_LOCAL_STORAGE_KEY, (resps) => {
-                    let cacheMonkeys, storageMode = false;
-                    if (!resps || !resps[PAGE_MONKEY_LOCAL_STORAGE_KEY]) {
-                        cacheMonkeys = localStorage.getItem(PAGE_MONKEY_LOCAL_STORAGE_KEY) || '[]';
-                        storageMode = true;
-                    } else {
-                        cacheMonkeys = resps[PAGE_MONKEY_LOCAL_STORAGE_KEY] || '[]';
-                    }
-
-                    params && params.url && handler(JSON.parse(cacheMonkeys));
-
-                    // 本地存储的内容,需要全部迁移到chrome.storage.local中,以确保unlimitedStorage
-                    if (storageMode) {
-                        let storageData = {};
-                        storageData[PAGE_MONKEY_LOCAL_STORAGE_KEY] = cacheMonkeys;
-                        chrome.storage.local.set(storageData);
-                    }
-                });
-
-            } catch (e) {
-                callback && callback(null);
-            }
-            return true;
-        }).toString()
+        }
     });
-};
+};

+ 0 - 1
apps/password/index.html

@@ -8,7 +8,6 @@
     <link rel="stylesheet" href="index.css" />
     <script type="text/javascript" src="../static/vendor/evalCore.min.js"></script>
     <script type="text/javascript" src="../static/vendor/vue/vue.js"></script>
-    <script src="../static/vendor/require/require.js"></script>
 </head>
 
 <body>

+ 0 - 1
apps/postman/index.html

@@ -8,7 +8,6 @@
         <link rel="stylesheet" href="index.css" />
         <script type="text/javascript" src="../static/vendor/evalCore.min.js"></script>
         <script type="text/javascript" src="../static/vendor/vue/vue.js"></script>
-        <script src="../static/vendor/require/require.js"></script>
     </head>
     <body class="theme-default">
 

+ 0 - 1
apps/timestamp/index.html

@@ -7,7 +7,6 @@
         <link rel="stylesheet" href="index.css" />
         <script type="text/javascript" src="../static/vendor/evalCore.min.js"></script>
         <script type="text/javascript" src="../static/vendor/vue/vue.js"></script>
-        <script type="text/javascript" src="../static/vendor/require/require.js"></script>
     </head>
     <body>