Parcourir la source

page-timing完善

[email protected] il y a 2 ans
Parent
commit
927ec25241

+ 130 - 10
apps/background/background.js

@@ -158,11 +158,11 @@ let BgPageInstance = (function () {
 
 
         // 如果是noPage模式,则表名只完成content-script的工作,直接发送命令即可
         // 如果是noPage模式,则表名只完成content-script的工作,直接发送命令即可
         if (configs.noPage) {
         if (configs.noPage) {
-            tool = new URL(`http://f.h?${tool}`).searchParams.get('tool').replace(/-/g, '');
+            let toolFunc = tool.replace(/-/g, '');
             chrome.tabs.query({active: true, currentWindow: true}, tabs => {
             chrome.tabs.query({active: true, currentWindow: true}, tabs => {
                 let found = tabs.some(tab => {
                 let found = tabs.some(tab => {
                     if (/^(http(s)?|file):\/\//.test(tab.url) && blacklist.every(reg => !reg.test(tab.url))) {
                     if (/^(http(s)?|file):\/\//.test(tab.url) && blacklist.every(reg => !reg.test(tab.url))) {
-                        let codes = `window['${tool}NoPage'] && window['${tool}NoPage'](${JSON.stringify(tab)});`;
+                        let codes = `window['${toolFunc}NoPage'] && window['${toolFunc}NoPage'](${JSON.stringify(tab)});`;
                         injectScriptIfTabExists(tab.id, {code: codes});
                         injectScriptIfTabExists(tab.id, {code: codes});
                         return true;
                         return true;
                     }
                     }
@@ -279,6 +279,118 @@ let BgPageInstance = (function () {
         });
         });
     };
     };
 
 
+    let _screenCapture = function(params){
+
+        // 将Blob数据存储到本地临时文件
+        function saveBlob(blob, filename, index, callback, errback) {
+            filename = ((filename, index) => {
+                if (!index) {
+                    return filename;
+                }
+                let sp = filename.split('.');
+                let ext = sp.pop();
+                return sp.join('.') + '-' + (index + 1) + '.' + ext;
+            })(filename, index);
+            let urlName = `filesystem:chrome-extension://${chrome.i18n.getMessage('@@extension_id')}/temporary/${filename}`;
+
+            let size = blob.size + (1024 / 2);
+
+            let reqFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
+            reqFileSystem(window.TEMPORARY, size, function (fs) {
+                fs.root.getFile(filename, {create: true}, function (fileEntry) {
+                    fileEntry.createWriter(function (fileWriter) {
+                        fileWriter.onwriteend = () => callback(urlName);
+                        fileWriter.write(blob);
+                    }, errback);
+                }, errback);
+            }, errback);
+        }
+
+        function reallyDone(imgUrl) {
+            params.fileSystemUrl = imgUrl;
+            let sendDataUri = tab => {
+                chrome.tabs.sendMessage(tab.id, {
+                    type: 'page-screenshot-done',
+                    data: params
+                });
+            };
+            if (!params.resultTab) {
+                chrome.tabs.create({
+                    url: 'dynamic/index.html?tool=screenshot',
+                    active: true
+                }, (tab) => {
+                    setTimeout((tab => {
+                        return () => sendDataUri(tab);
+                    })(tab), 500);
+                });
+            } else {
+                chrome.tabs.update(params.resultTab, {highlighted: true, active: true}, sendDataUri);
+            }
+        }
+
+        // 获取Blobs数据
+        function getBlobs(dataUris) {
+            return dataUris.map(function (uri) {
+                let byteString = atob(uri.split(',')[1]);
+                let mimeString = uri.split(',')[0].split(':')[1].split(';')[0];
+                let ab = new ArrayBuffer(byteString.length);
+                let ia = new Uint8Array(ab);
+                for (let i = 0; i < byteString.length; i++) {
+                    ia[i] = byteString.charCodeAt(i);
+                }
+                return new Blob([ab], {type: mimeString});
+            });
+        }
+
+        function wellDone(dus) {
+            let blobs = getBlobs(dus);
+            let i = 0;
+            let len = blobs.length;
+
+            // 保存 & 打开
+            (function doNext() {
+                saveBlob(blobs[i], params.filename, i, function (imgUrl) {
+                    ++i >= len ? reallyDone(imgUrl) : doNext();
+                }, reallyDone);
+            })();
+        }
+
+        wellDone(params.dataUris);
+    };
+
+    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 });
+        });
+
+        let code = `window.addScreenShot(${JSON.stringify(params)},'${uri}');`
+        injectScriptIfTabExists(params.tabInfo.id, { code: `window.captureCallback();` });
+    };
+
+    let _colorPickerCapture = function(params) {
+        chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
+            chrome.tabs.captureVisibleTab(null, {format: 'png'}, function (dataUrl) {
+                let code = `window.colorpickerNoPage(${JSON.stringify({
+                    setPickerImage: true,
+                    pickerImage: dataUrl
+                })})`;
+                injectScriptIfTabExists(tabs[0].id, { code });
+            });
+        });
+    };
+
+    let _codeBeautify = function(params){
+        if (['javascript', 'css'].includes(params.fileType)) {
+            Awesome.StorageMgr.get('JS_CSS_PAGE_BEAUTIFY').then(val => {
+                if(val !== '0') {
+                    let code = `window._codebutifydetect_('${params.fileType}')`;
+                    injectScriptIfTabExists(params.tabId, { code });
+                }
+            });
+        }
+    };
+
     /**
     /**
      * 接收来自content_scripts发来的消息
      * 接收来自content_scripts发来的消息
      */
      */
@@ -324,14 +436,7 @@ let BgPageInstance = (function () {
                         });
                         });
                         break;
                         break;
                     case 'code-beautify':
                     case 'code-beautify':
-                        if (['javascript', 'css'].includes(request.params.fileType)) {
-                            Awesome.StorageMgr.get('JS_CSS_PAGE_BEAUTIFY').then(val => {
-                                if(val !== '0') {
-                                    let code = `window._codebutifydetect_('${request.params.fileType}')`;
-                                    injectScriptIfTabExists(request.params.tabId, { code });
-                                }
-                            });
-                        }
+                        _codeBeautify(request.params);
                         break;
                         break;
                     case 'close-beautify':
                     case 'close-beautify':
                         Awesome.StorageMgr.set('JS_CSS_PAGE_BEAUTIFY',0);
                         Awesome.StorageMgr.set('JS_CSS_PAGE_BEAUTIFY',0);
@@ -347,6 +452,21 @@ let BgPageInstance = (function () {
                         request.params = FeJson[request.tabId];
                         request.params = FeJson[request.tabId];
                         delete FeJson[request.tabId];
                         delete FeJson[request.tabId];
                         break;
                         break;
+                    case 'set-page-timing-data':
+                        chrome.DynamicToolRunner({
+                            tool: 'page-timing',
+                            withContent: request.wpoInfo
+                        });
+                        break;
+                    case 'color-picker-capture':
+                        _colorPickerCapture(request.params);
+                        break;
+                    case 'screen-capture':
+                        _screenCapture(request.params);
+                        break;
+                    case 'add-screen-shot-by-pages':
+                        _addScreenShotByPages(request.params);
+                        break;
                 }
                 }
                 callback && callback(request.params);
                 callback && callback(request.params);
             } else {
             } else {

+ 4 - 0
apps/background/tools.js

@@ -163,6 +163,7 @@ let toolMap = {
         name: '网页截屏工具',
         name: '网页截屏工具',
         tips: '可对任意网页进行截屏,支持可视区域截屏、全网页滚动截屏,最终结果可预览后再保存',
         tips: '可对任意网页进行截屏,支持可视区域截屏、全网页滚动截屏,最终结果可预览后再保存',
         contentScriptJs: true,
         contentScriptJs: true,
+        // noPage: true,
         menuConfig: [{
         menuConfig: [{
             icon: '✂',
             icon: '✂',
             text: 'FH开发者工具'
             text: 'FH开发者工具'
@@ -172,6 +173,7 @@ let toolMap = {
         name: '页面取色工具',
         name: '页面取色工具',
         tips: '可直接在网页上针对任意元素进行色值采集,将光标移动到需要取色的位置,单击确定即可',
         tips: '可直接在网页上针对任意元素进行色值采集,将光标移动到需要取色的位置,单击确定即可',
         contentScriptJs: true,
         contentScriptJs: true,
+        noPage: true,
         menuConfig: [{
         menuConfig: [{
             icon: '✑',
             icon: '✑',
             text: 'FH开发者工具'
             text: 'FH开发者工具'
@@ -190,6 +192,7 @@ let toolMap = {
         tips: 'Web开发用,横竖两把尺子,以10px为单位,用以检测&校准当前网页的栅格对齐率',
         tips: 'Web开发用,横竖两把尺子,以10px为单位,用以检测&校准当前网页的栅格对齐率',
         contentScriptJs: true,
         contentScriptJs: true,
         contentScriptCss: true,
         contentScriptCss: true,
+        noPage: true,
         menuConfig: [{
         menuConfig: [{
             icon: 'Ⅲ',
             icon: 'Ⅲ',
             text: 'FH开发者工具'
             text: 'FH开发者工具'
@@ -199,6 +202,7 @@ let toolMap = {
         name: '网页性能检测',
         name: '网页性能检测',
         tips: '检测网页加载性能,包括握手、响应、渲染等各阶段耗时,同时提供Response Headers以便分析',
         tips: '检测网页加载性能,包括握手、响应、渲染等各阶段耗时,同时提供Response Headers以便分析',
         contentScriptJs: true,
         contentScriptJs: true,
+        noPage: true,
         menuConfig: [{
         menuConfig: [{
             icon: 'Σ',
             icon: 'Σ',
             text: 'FH开发者工具'
             text: 'FH开发者工具'

+ 3 - 22
apps/color-picker/content-script.js

@@ -404,29 +404,10 @@ window.colorpickerContentScript = function () {
                 try {
                 try {
                     chrome.runtime.sendMessage({
                     chrome.runtime.sendMessage({
                         type: 'fh-dynamic-any-thing',
                         type: 'fh-dynamic-any-thing',
+                        thing:'color-picker-capture',
                         params: {
                         params: {
                             url: location.href
                             url: location.href
-                        },
-                        func: ((params, callback) => {
-                            try {
-                                chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
-                                    chrome.tabs.captureVisibleTab(null, {format: 'png'}, function (dataUrl) {
-                                        chrome.tabs.executeScript(tabs[0].id, {
-                                            code: `(` + ((data) => {
-                                                window.colorpickerNoPage(data);
-                                            }).toString() + `)(${JSON.stringify({
-                                                setPickerImage: true,
-                                                pickerImage: dataUrl
-                                            })})`
-                                        });
-                                    });
-                                });
-                            } catch (e) {
-                            }
-                            callback && callback(null);
-                            return true;
-                        }).toString()
-                    }, function () {
+                        }
                     });
                     });
                 } catch (e) {
                 } catch (e) {
                     console.log('有错误发生,可提交此反馈到官网!', e);
                     console.log('有错误发生,可提交此反馈到官网!', e);
@@ -558,4 +539,4 @@ window.colorpickerContentScript = function () {
     window.colorpickerNoPage = function (request) {
     window.colorpickerNoPage = function (request) {
         FeHelper.ColorPicker(request)
         FeHelper.ColorPicker(request)
     };
     };
-};
+};

+ 0 - 13
apps/color-picker/index.html

@@ -1,13 +0,0 @@
-<!doctype html>
-<html lang="en">
-<head>
-    <meta charset="UTF-8">
-    <meta name="viewport"
-          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
-    <meta http-equiv="X-UA-Compatible" content="ie=edge">
-    <title>页面取色工具</title>
-</head>
-<body>
-<script type="text/javascript" src="content-script.js"></script>
-</body>
-</html>

+ 3 - 1
apps/manifest.json

@@ -60,7 +60,9 @@
             "static/vendor/evalCore.min.js",
             "static/vendor/evalCore.min.js",
 
 
             "code-beautify/beautify.js",
             "code-beautify/beautify.js",
-            "code-beautify/beautify-css.js"
+            "code-beautify/beautify-css.js",
+
+            "page-timing/timing.js"
         ],
         ],
         "matches": ["<all_urls>"]
         "matches": ["<all_urls>"]
       }
       }

+ 20 - 23
apps/page-timing/content-script.js

@@ -5,12 +5,25 @@
 window.pagetimingContentScript = function () {
 window.pagetimingContentScript = function () {
 
 
     let __importScript = (filename) => {
     let __importScript = (filename) => {
-        fetch(filename).then(resp => resp.text()).then(jsText => eval(jsText));
+        pleaseLetJsLoaded = 100;
+        let url = filename;
+
+        if (location.protocol === 'chrome-extension:' || chrome.runtime && chrome.runtime.getURL) {
+            url = chrome.runtime.getURL('page-timing/' + filename);
+        }
+        fetch(url).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);
+        });
     };
     };
 
 
     __importScript('timing.js');
     __importScript('timing.js');
 
 
-    let DetectMgr = (() => {
+    window.pagetimingNoPage = function() {
 
 
         let wpoInfo = {
         let wpoInfo = {
             pageInfo: {
             pageInfo: {
@@ -23,18 +36,8 @@ window.pagetimingContentScript = function () {
         let sendWpoInfo = function () {
         let sendWpoInfo = function () {
             chrome.runtime.sendMessage({
             chrome.runtime.sendMessage({
                 type: 'fh-dynamic-any-thing',
                 type: 'fh-dynamic-any-thing',
-                params: {
-                    tabId: window.__FH_TAB_ID__ || null,
-                    wpoInfo: wpoInfo
-                },
-                func: ((params, callback) => {
-                    chrome.DynamicToolRunner({
-                        query: 'tool=page-timing',
-                        withContent: params.wpoInfo
-                    });
-                    callback && callback();
-                    return true;
-                }).toString()
+                thing: 'set-page-timing-data',
+                wpoInfo: wpoInfo
             });
             });
         };
         };
 
 
@@ -64,13 +67,7 @@ window.pagetimingContentScript = function () {
             }
             }
         };
         };
 
 
-        return {
-            detect: detect
-        };
-    })();
-
-
-    window.pagetimingNoPage = function () {
-        DetectMgr.detect();
+        detect();
     };
     };
-};
+
+};

+ 0 - 2
apps/page-timing/index.html

@@ -6,7 +6,6 @@
         <link rel="stylesheet" href="index.css" />
         <link rel="stylesheet" href="index.css" />
         <script type="text/javascript" src="../static/vendor/evalCore.min.js"></script>
         <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/vue/vue.js"></script>
-        <script type="text/javascript" src="../static/vendor/require/require.js"></script>
     </head>
     </head>
     <body>
     <body>
 
 
@@ -63,6 +62,5 @@
     </div>
     </div>
 
 
     <script type="text/javascript" src="index.js"></script>
     <script type="text/javascript" src="index.js"></script>
-    <script type="text/javascript" src="content-script.js"></script>
     </body>
     </body>
 </html>
 </html>

+ 13 - 8
apps/page-timing/index.js

@@ -26,13 +26,18 @@ new Vue({
     mounted: function () {
     mounted: function () {
         // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
         // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
         if (location.protocol === 'chrome-extension:') {
         if (location.protocol === 'chrome-extension:') {
-            chrome.runtime.onMessage.addListener((request, sender, callback) => {
-                if (request.type === 'TAB_CREATED_OR_UPDATED' && request.content && request.event === location.pathname.split('/')[1]) {
-                    sessionStorage.setItem('wpo-data', JSON.stringify(request.content));
-                    this.showTiming(request.content);
-                }
-                callback && callback();
-                return true;
+            chrome.tabs.query({currentWindow: true,active: true, }, (tabs) => {
+                let activeTab = tabs.filter(tab => tab.active)[0];
+                chrome.runtime.sendMessage({
+                    type: 'fh-dynamic-any-thing',
+                    thing: 'request-page-content',
+                    tabId: activeTab.id
+                }).then(resp => {
+                    console.log(resp)
+                    if(!resp && !resp.content) return ;
+                    sessionStorage.setItem('wpo-data', JSON.stringify(resp.content));
+                    this.showTiming(resp.content);
+                });
             });
             });
         }
         }
 
 
@@ -49,4 +54,4 @@ new Vue({
             this.headerInfo = wpo.header;
             this.headerInfo = wpo.header;
         },
         },
     }
     }
-});
+});

+ 1 - 1
apps/popup/index.js

@@ -69,7 +69,7 @@ new Vue({
                 page: toolName,
                 page: toolName,
                 noPage: !!noPage
                 noPage: !!noPage
             });
             });
-
+            !!noPage && setTimeout(window.close,200);
         },
         },
 
 
         openOptionsPage: () => {
         openOptionsPage: () => {

+ 4 - 92
apps/screenshot/content-script.js

@@ -191,86 +191,8 @@ window.screenshotContentScript = function (params) {
 
 
             chrome.runtime.sendMessage({
             chrome.runtime.sendMessage({
                 type: 'fh-dynamic-any-thing',
                 type: 'fh-dynamic-any-thing',
-                params: capturedData,
-                func: ((params,csCallback) => {
-
-                    // 将Blob数据存储到本地临时文件
-                    function saveBlob(blob, filename, index, callback, errback) {
-                        filename = ((filename, index) => {
-                            if (!index) {
-                                return filename;
-                            }
-                            let sp = filename.split('.');
-                            let ext = sp.pop();
-                            return sp.join('.') + '-' + (index + 1) + '.' + ext;
-                        })(filename, index);
-                        let urlName = `filesystem:chrome-extension://${chrome.i18n.getMessage('@@extension_id')}/temporary/${filename}`;
-
-                        let size = blob.size + (1024 / 2);
-
-                        let reqFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
-                        reqFileSystem(window.TEMPORARY, size, function (fs) {
-                            fs.root.getFile(filename, {create: true}, function (fileEntry) {
-                                fileEntry.createWriter(function (fileWriter) {
-                                    fileWriter.onwriteend = () => callback(urlName);
-                                    fileWriter.write(blob);
-                                }, errback);
-                            }, errback);
-                        }, errback);
-                    }
-
-                    function reallyDone(imgUrl) {
-                        params.fileSystemUrl = imgUrl;
-                        let sendDataUri = tab => {
-                            chrome.tabs.sendMessage(tab.id, {
-                                type: 'page-screenshot-done',
-                                data: params
-                            });
-                        };
-                        if (!params.resultTab) {
-                            chrome.tabs.create({
-                                url: 'dynamic/index.html?tool=screenshot',
-                                active: true
-                            }, (tab) => {
-                                setTimeout((tab => {
-                                    return () => sendDataUri(tab);
-                                })(tab), 500);
-                            });
-                        } else {
-                            chrome.tabs.update(params.resultTab, {highlighted: true, active: true}, sendDataUri);
-                        }
-                    }
-
-                    // 获取Blobs数据
-                    function getBlobs(dataUris) {
-                        return dataUris.map(function (uri) {
-                            let byteString = atob(uri.split(',')[1]);
-                            let mimeString = uri.split(',')[0].split(':')[1].split(';')[0];
-                            let ab = new ArrayBuffer(byteString.length);
-                            let ia = new Uint8Array(ab);
-                            for (let i = 0; i < byteString.length; i++) {
-                                ia[i] = byteString.charCodeAt(i);
-                            }
-                            return new Blob([ab], {type: mimeString});
-                        });
-                    }
-
-                    function wellDone(dus) {
-                        let blobs = getBlobs(dus);
-                        let i = 0;
-                        let len = blobs.length;
-
-                        // 保存 & 打开
-                        (function doNext() {
-                            saveBlob(blobs[i], params.filename, i, function (imgUrl) {
-                                ++i >= len ? reallyDone(imgUrl) : doNext();
-                            }, reallyDone);
-                        })();
-                    }
-
-                    wellDone(params.dataUris);
-                    csCallback && csCallback();
-                }).toString()
+                thing: 'screen-capture',
+                params: capturedData
             });
             });
         },
         },
 
 
@@ -427,18 +349,8 @@ window.screenshotContentScript = function (params) {
 
 
                 chrome.runtime.sendMessage({
                 chrome.runtime.sendMessage({
                     type: 'fh-dynamic-any-thing',
                     type: 'fh-dynamic-any-thing',
-                    params: data,
-                    func: ((params, csCallback) => {
-                        chrome.tabs.captureVisibleTab(null, {format: 'png', quality: 100}, uri => {
-                            chrome.tabs.executeScript(params.tabInfo.id, {
-                                code: `window.addScreenShot(${JSON.stringify(params)},'${uri}');`
-                            });
-                        });
-                        chrome.tabs.executeScript(params.tabInfo.id, {
-                            code: `window.captureCallback();`
-                        });
-                        return true;
-                    }).toString()
+                    thing: 'add-screen-shot-by-pages',
+                    params: data
                 });
                 });
             }, 150);
             }, 150);
         })();
         })();

+ 13 - 0
apps/screenshot/index.js

@@ -97,6 +97,19 @@ new Vue({
                     if (found) {
                     if (found) {
                         chrome.tabs.update(tabId, {highlighted: true, active: true}, tab => {
                         chrome.tabs.update(tabId, {highlighted: true, active: true}, tab => {
 
 
+                            // 没有文件就只注入脚本
+                            // chrome.scripting.executeScript({
+                            //     target: {tab.id, allFrames: false},
+                            //     func: function(code){evalCore.getEvalInstance(window)(code)},
+                            //     args: [codeConfig.code]
+                            // }, function () {
+                            //     try {
+                            //         callback && callback.apply(this, arguments);
+                            //     } catch (e) {
+                            //         callback && callback(null);
+                            //     }
+                            // });
+
                             chrome.tabs.executeScript(tab.id, {
                             chrome.tabs.executeScript(tab.id, {
                                 code: '(' + (function (tabInfo, captureInfo) {
                                 code: '(' + (function (tabInfo, captureInfo) {
                                     chrome.runtime.sendMessage({
                                     chrome.runtime.sendMessage({