Browse Source

context menu fix

[email protected] 3 years ago
parent
commit
8f3a0c156d
3 changed files with 45 additions and 156 deletions
  1. 18 25
      apps/background/background.js
  2. 25 129
      apps/background/menu.js
  3. 2 2
      apps/json-format/index.js

+ 18 - 25
apps/background/background.js

@@ -177,22 +177,6 @@ let BgPageInstance = (function () {
             return;
         }
 
-        // 创建或更新成功执行的动作
-        let _tabUpdatedCallback = function (toolName, content) {
-            return function (newTab) {
-                setTimeout(function () {
-                    chrome.tabs.query({active: true, currentWindow: true}, tabs => {
-                        tabs && tabs.length && chrome.tabs.sendMessage(newTab.id, {
-                            type: MSG_TYPE.TAB_CREATED_OR_UPDATED,
-                            content: content,
-                            event: toolName,
-                            fromTab: activeTab
-                        });
-                    });
-                }, 300);
-            };
-        };
-
         chrome.tabs.query({currentWindow: true}, function (tabs) {
 
             activeTab = tabs.filter(tab => tab.active)[0];
@@ -213,13 +197,18 @@ let BgPageInstance = (function () {
                     }
                 }
 
+                let messageData = {
+                    type: MSG_TYPE.TAB_CREATED_OR_UPDATED,
+                    content: withContent,
+                    event: tool
+                };
                 if (!isOpened) {
                     chrome.tabs.create({
                         url: `/${tool}/index.html` + (query ? "?" + query : ''),
                         active: true
-                    }, _tabUpdatedCallback(tool, withContent));
+                    }).then(tab => { FeJson[tab.id] = messageData; });
                 } else {
-                    chrome.tabs.update(tabId, {highlighted: true}, _tabUpdatedCallback(tool, withContent));
+                    chrome.tabs.update(tabId, {highlighted: true}).then(tab => { FeJson[tab.id] = messageData; });
                 }
 
             });
@@ -300,7 +289,7 @@ let BgPageInstance = (function () {
         chrome.runtime.onMessage.addListener(function (request, sender, callback) {
             // 如果发生了错误,就啥都别干了
             if (chrome.runtime.lastError) {
-                console.log(chrome.runtime.lastError);
+                console.log('chrome.runtime.lastError:',chrome.runtime.lastError);
                 return true;
             }
 
@@ -369,13 +358,17 @@ let BgPageInstance = (function () {
         // 每开一个窗口,都向内容脚本注入一个js,绑定tabId
         chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
 
-            if (String(changeInfo.status).toLowerCase() === "complete"
-                && /^(http(s)?|file):\/\//.test(tab.url)
-                && blacklist.every(reg => !reg.test(tab.url))) {
+            if (String(changeInfo.status).toLowerCase() === "complete") {
 
-                injectScriptIfTabExists(tabId, { code: `window.__FH_TAB_ID__=${tabId};` });
-
-                _injectContentScripts(tabId);
+                if(/^(http(s)?|file):\/\//.test(tab.url) && blacklist.every(reg => !reg.test(tab.url))){
+                    injectScriptIfTabExists(tabId, { code: `window.__FH_TAB_ID__=${tabId};` });
+                    _injectContentScripts(tabId);
+                }else if(/^chrome\-extension\:\/\//.test(tab.url)){
+                    if(FeJson[tab.id]) {
+                        chrome.runtime.sendMessage(FeJson[tab.id]);
+                        delete FeJson[tab.id];
+                    }
+                }
             }
         });
 

+ 25 - 129
apps/background/menu.js

@@ -42,145 +42,47 @@ export default (function () {
                     toolMap[tool].menuConfig[0].onClick = function (info, tab) {
                         chrome.scripting.executeScript({
                             target: {tabId:tab.id,allFrames:false},
-                            func: () => info.selectionText
-                        }, txt => chrome.DynamicToolRunner({
-                            tool: 'json-format',
-                            withContent: txt[0]
+                            args: [info.selectionText],
+                            func: (text) => text
+                        }, resp => chrome.DynamicToolRunner({
+                            tool, withContent: resp[0].result
                         }));
-
-                        // chrome.tabs.executeScript(tab.id, {
-                        //     code: '(' + (function (pInfo) {
-                        //         return pInfo.selectionText;
-                        //     }).toString() + ')(' + JSON.stringify(info) + ')',
-                        //     allFrames: false
-                        // }, function (txt) {
-                        //     chrome.DynamicToolRunner({
-                        //         tool: 'json-format',
-                        //         withContent: txt[0]
-                        //     });
-                        // });
                     };
                     break;
 
                 case 'code-beautify':
                 case 'en-decode':
                     toolMap[tool].menuConfig[0].onClick = 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) {
-                            chrome.DynamicToolRunner({
-                                withContent: txt[0],
-                                query: `tool=${tool}`
-                            });
-                        });
+                        chrome.scripting.executeScript({
+                            target: {tabId:tab.id,allFrames:false},
+                            args: [info.linkUrl || info.srcUrl || info.selectionText || info.pageUrl],
+                            func: (text) => text
+                        }, resp => chrome.DynamicToolRunner({
+                            tool, withContent: resp[0].result
+                        }));
                     };
                     break;
 
 
                 case 'qr-code':
                     toolMap[tool].menuConfig[0].onClick = 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) {
-                            chrome.DynamicToolRunner({
-                                withContent: txt[0],
-                                query: `tool=qr-code`
-                            });
-                        });
+                        chrome.scripting.executeScript({
+                            target: {tabId:tab.id,allFrames:false},
+                            args: [info.linkUrl || info.srcUrl || info.selectionText || info.pageUrl],
+                            func: (text) => text
+                        }, resp => chrome.DynamicToolRunner({
+                            tool, withContent: resp[0].result
+                        }));
                     };
                     toolMap[tool].menuConfig[1].onClick = function (info, tab) {
-
-                        // V2020.2.618之前的版本都用这个方法
-                        let funForLowerVer = function () {
-                            chrome.tabs.executeScript(tab.id, {
-                                code: '(' + (function (pInfo) {
-                                    function loadImage(src) {
-                                        return new Promise(resolve => {
-                                            let image = new Image();
-                                            image.setAttribute('crossOrigin', 'Anonymous');
-                                            image.src = src;
-                                            image.onload = function () {
-                                                let width = this.naturalWidth;
-                                                let height = this.naturalHeight;
-                                                let canvas = document.createElement('canvas');
-                                                canvas.style.cssText = 'position:absolute;top:-10000px;left:-10000px';
-                                                document.body.appendChild(canvas);
-                                                canvas.setAttribute('id', 'qr-canvas');
-                                                canvas.height = height + 100;
-                                                canvas.width = width + 100;
-                                                let context = canvas.getContext('2d');
-                                                context.fillStyle = 'rgb(255,255,255)';
-                                                context.fillRect(0, 0, canvas.width, canvas.height);
-                                                context.drawImage(image, 0, 0, width, height, 50, 50, width, height);
-                                                resolve(canvas.toDataURL());
-                                            };
-                                            image.onerror = function () {
-                                                resolve(src);
-                                            };
-                                        });
-                                    }
-
-                                    let tempDataUrl = '__TEMP_DATA_URL_FOR_QRDECODE_';
-                                    loadImage(pInfo.srcUrl).then(dataUrl => {
-                                        window[tempDataUrl] = dataUrl;
-                                    });
-
-                                    return tempDataUrl;
-
-                                }).toString() + ')(' + JSON.stringify(info) + ')',
-                                allFrames: false
-                            }, function (resp) {
-                                let tempDataUrl = resp[0];
-                                let intervalId = -1;
-                                let repeatTime = 0;
-                                let loop = function () {
-                                    repeatTime++;
-                                    intervalId = setInterval(function () {
-                                        chrome.tabs.executeScript(tab.id, {
-                                            code: '(' + (function (tempDataUrl) {
-                                                return window[tempDataUrl];
-                                            }).toString() + ')(' + JSON.stringify(tempDataUrl) + ')',
-                                            allFrames: false
-                                        }, function (arr) {
-                                            if (arr[0] === null && repeatTime <= 10) {
-                                                loop();
-                                            } else {
-                                                clearInterval(intervalId);
-                                                chrome.DynamicToolRunner({
-                                                    withContent: arr[0] || info.srcUrl,
-                                                    query: `tool=qr-code&mode=decode`
-                                                });
-                                            }
-                                        });
-                                    }, 200);
-                                };
-                                loop();
-                            });
-                        };
-
-                        chrome.tabs.executeScript(tab.id, {
-                            code: '(' + (function (pInfo) {
+                        chrome.scripting.executeScript({
+                            target: {tabId:tab.id,allFrames:false},
+                            args: [info.srcUrl],
+                            func: (text) => {
                                 try {
                                     if (typeof window.qrcodeContentScript === 'function') {
                                         let qrcode = window.qrcodeContentScript();
                                         if (typeof qrcode.decode === 'function') {
-                                            // 直接解码
                                             qrcode.decode(pInfo.srcUrl);
                                             return 1;
                                         }
@@ -188,22 +90,16 @@ export default (function () {
                                 } catch (e) {
                                     return 0;
                                 }
-                                return 0;
-                            }).toString() + ')(' + JSON.stringify(info) + ')',
-                            allFrames: false
-                        }, function (resp) {
-                            (resp[0] === 0) && funForLowerVer();
+                            }
                         });
-
                     };
                     break;
 
                 default:
                     toolMap[tool].menuConfig[0].onClick = function (info, tab) {
                         chrome.DynamicToolRunner({
-                            withContent: tool === 'image-base64' ? info.srcUrl : '',
-                            query: `tool=${tool}`
-                        });
+                            tool, withContent: tool === 'image-base64' ? info.srcUrl : ''
+                        })
                     };
                     break;
             }

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

@@ -66,8 +66,8 @@ new Vue({
                 if (request.type === 'TAB_CREATED_OR_UPDATED' && request.content && request.event === location.pathname.split('/')[1]) {
                     editor.setValue(request.content || this.defaultResultTpl);
                     this.format();
+                    callback && callback();
                 }
-                callback && callback();
                 return true;
             });
         }
@@ -174,7 +174,7 @@ new Vue({
                     return false;
                 }
             }
-            
+
             return true;
         },