From 33200dbde4ac1903813754a3c7701f0b4ed780fa Mon Sep 17 00:00:00 2001 From: eight Date: Tue, 12 Sep 2017 18:34:48 +0800 Subject: [PATCH] Fix: cleanup injectContent --- background/background.js | 39 +++++++------------------------------ content/install-user-css.js | 2 +- 2 files changed, 8 insertions(+), 33 deletions(-) diff --git a/background/background.js b/background/background.js index 678c77d0..072848e7 100644 --- a/background/background.js +++ b/background/background.js @@ -324,46 +324,21 @@ function onRuntimeMessage(request, sender, sendResponse) { return KEEP_CHANNEL_OPEN; case 'injectContent': - injectContent(request, sender.tab.id).then(sendResponse); + injectContent(sender.tab.id, request).then(sendResponse); return KEEP_CHANNEL_OPEN; } } -function injectContent({resources}, tabId) { - return Promise.all(doInject()) +function injectContent(tabId, {files}) { + return Promise.all(files.map(inject)) .then(() => ({status: 'success'})) .catch(err => ({status: 'error', error: err.message})); - function *doInject() { - for (const resource of resources) { - const type = resource.match(/\.\w+$/i)[0]; - if (type === '.js') { - yield injectScript(resource, tabId); - } else if (type === '.css') { - yield injectStyle(resource, tabId); - } - } - } - - function injectScript(url, tabId) { + function inject(file) { return new Promise((resolve, reject) => { - chrome.tabs.executeScript(tabId, { - file: url, - runAt: 'document_start' - }, () => { - if (chrome.runtime.lastError) { - reject(chrome.runtime.lastError); - } else { - resolve(); - } - }); - }); - } - - function injectStyle(url, tabId) { - return new Promise((resolve, reject) => { - chrome.tabs.insertCSS(tabId, { - file: url, + const method = file.endsWith('.js') ? 'executeScript' : 'insertCSS'; + chrome.tabs[method](tabId, { + file, runAt: 'document_start' }, () => { if (chrome.runtime.lastError) { diff --git a/content/install-user-css.js b/content/install-user-css.js index ec3aaeb5..05273e31 100644 --- a/content/install-user-css.js +++ b/content/install-user-css.js @@ -232,7 +232,7 @@ function createSourceLoader() { function initUsercssInstall() { pendingResource = communicate({ method: 'injectContent', - resources: [ + files: [ '/js/dom.js', '/js/localization.js', '/js/usercss.js',