From 115c3ce3d74188bb33d73f33f7546d05d6acbee8 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sat, 24 Sep 2022 16:41:21 -0400 Subject: [PATCH] API loadExtensionScripts (#2233) * Inject MV3 scripts immediately * Add api.loadExtensionScripts --- ext/js/background/backend.js | 13 ++++++++++++- ext/js/background/script-manager.js | 1 + ext/js/comm/api.js | 4 ++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/ext/js/background/backend.js b/ext/js/background/backend.js index a3694dd3..20402539 100644 --- a/ext/js/background/backend.js +++ b/ext/js/background/backend.js @@ -130,7 +130,8 @@ class Backend { ['testMecab', {async: true, contentScript: true, handler: this._onApiTestMecab.bind(this)}], ['textHasJapaneseCharacters', {async: false, contentScript: true, handler: this._onApiTextHasJapaneseCharacters.bind(this)}], ['getTermFrequencies', {async: true, contentScript: true, handler: this._onApiGetTermFrequencies.bind(this)}], - ['findAnkiNotes', {async: true, contentScript: true, handler: this._onApiFindAnkiNotes.bind(this)}] + ['findAnkiNotes', {async: true, contentScript: true, handler: this._onApiFindAnkiNotes.bind(this)}], + ['loadExtensionScripts', {async: true, contentScript: true, handler: this._onApiLoadExtensionScripts.bind(this)}] ]); this._messageHandlersWithProgress = new Map([ ]); @@ -771,6 +772,16 @@ class Backend { return await this._anki.findNotes(query); } + async _onApiLoadExtensionScripts({files}, sender) { + if (!sender || !sender.tab) { throw new Error('Invalid sender'); } + const tabId = sender.tab.id; + if (typeof tabId !== 'number') { throw new Error('Sender has invalid tab ID'); } + const {frameId} = sender; + for (const file of files) { + await this._scriptManager.injectScript(file, tabId, frameId, false, true, 'document_start'); + } + } + // Command handlers async _onCommandOpenSearchPage(params) { diff --git a/ext/js/background/script-manager.js b/ext/js/background/script-manager.js index 17b95242..3deb74fe 100644 --- a/ext/js/background/script-manager.js +++ b/ext/js/background/script-manager.js @@ -290,6 +290,7 @@ class ScriptManager { _injectScriptMV3(file, tabId, frameId, allFrames) { return new Promise((resolve, reject) => { const details = { + injectImmediately: true, files: [file], target: {tabId, allFrames} }; diff --git a/ext/js/comm/api.js b/ext/js/comm/api.js index 2ffe2d8c..2adc9a99 100644 --- a/ext/js/comm/api.js +++ b/ext/js/comm/api.js @@ -176,6 +176,10 @@ class API { return this._invoke('findAnkiNotes', {query}); } + loadExtensionScripts(files) { + return this._invoke('loadExtensionScripts', {files}); + } + // Utilities _createActionPort(timeout=5000) {