From c6c0126394f4bf5862061aaa5be7f941ff957a07 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sat, 18 Jul 2020 14:18:10 -0400 Subject: Content script ready checks (#670) * Move ready checkout of Display * Add function to wait until if a tab's content script is ready --- ext/bg/js/backend.js | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) (limited to 'ext/bg') diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js index f17e8897..301fe135 100644 --- a/ext/bg/js/backend.js +++ b/ext/bg/js/backend.js @@ -1383,4 +1383,59 @@ class Backend { // Edge throws exception for no reason here. } } + + _waitUntilTabFrameIsReady(tabId, frameId, timeout=null) { + return new Promise((resolve, reject) => { + let timer = null; + let onMessage = (message, sender) => { + if ( + !sender.tab || + sender.tab.id !== tabId || + sender.frameId !== frameId || + !isObject(message) || + message.action !== 'yomichanCoreReady' + ) { + return; + } + + cleanup(); + resolve(); + }; + const cleanup = () => { + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + if (onMessage !== null) { + chrome.runtime.onMessage.removeListener(onMessage); + onMessage = null; + } + }; + + chrome.runtime.onMessage.addListener(onMessage); + + chrome.tabs.sendMessage(tabId, {action: 'isReady'}, {frameId}, (response) => { + const error = chrome.runtime.lastError; + if (error) { return; } + + try { + const value = yomichan.getMessageResponseResult(response); + if (!value) { return; } + + cleanup(); + resolve(); + } catch (e) { + // NOP + } + }); + + if (timeout !== null) { + timer = setTimeout(() => { + timer = null; + cleanup(); + reject(new Error('Timeout')); + }, timeout); + } + }); + } } -- cgit v1.2.3