diff --git a/plugin/js/main.js b/plugin/js/main.js index 38ebe0e1..6edf6b9a 100644 --- a/plugin/js/main.js +++ b/plugin/js/main.js @@ -269,7 +269,7 @@ var main = (function() { function populateControls() { loadUserPreferences(); parserFactory.populateManualParserSelectionTag(getManuallySelectParserTag()); - configureForTabMode(); + importPageFromTabIdInUrl(); } function loadUserPreferences() { @@ -280,10 +280,26 @@ var main = (function() { BakaTsukiSeriesPageParser.registerBakaParsers(userPreferences.autoSelectBTSeriesPage.value); } - function isRunningInTabMode() { - // if query string supplied, we're running in Tab mode. - let search = window.location.search; - return !util.isNullOrEmpty(search); + async function isOpenInBrowserTab() { + // Clicking the toolbar icon first loads bare popup.html in the popup. + // That popup opens popup.html?id= in a browser tab and closes. + // The query string marks that second load, so it can initialize in place. + const hasQueryString = !util.isNullOrEmpty(window.location.search); + if (hasQueryString) { + return true; + } + + // The address bar, a bookmark, or a homepage can also open bare popup.html. + // getCurrent() returns that browser tab and returns undefined in the popup. + // Without this check, a direct open would launch a second tab and try to + // inject into the first WebToEpub tab, causing Firefox's + // "Missing host permission for the tab" error. + const isFirefox = util.isFirefox(); + const currentTab = isFirefox + ? await browser.tabs.getCurrent() + : await chrome.tabs.getCurrent(); + const hasCurrentTab = currentTab != null; + return hasCurrentTab; } async function populateControlsWithDom(url, dom) { @@ -401,14 +417,19 @@ var main = (function() { } } - function configureForTabMode() { - getActiveTabDOM(extractTabIdFromQueryParameter()); - } + function importPageFromTabIdInUrl() { + // A bare popup.html link can open the library or settings without a + // source page. Skip the tab lookup and injection for that launch. + const sourceTabIdParam = new URLSearchParams(window.location.search).get("id"); + const hasSourceTabId = !util.isNullOrEmpty(sourceTabIdParam); + if (!hasSourceTabId) { + return; + } - function extractTabIdFromQueryParameter() { - let windowId = window.location.search.split("=")[1]; - if (!util.isNullOrEmpty(windowId)) { - return parseInt(windowId, 10); + const sourceTabId = Number(sourceTabIdParam); + const isSourceTabIdWellFormed = Number.isSafeInteger(sourceTabId) && sourceTabId >= 0; + if (isSourceTabIdWellFormed) { + getActiveTabDOM(sourceTabId); } } @@ -665,7 +686,7 @@ var main = (function() { return; } userPreferences = UserPreferences.readFromLocalStorage(); - if (isRunningInTabMode()) { + if (await isOpenInBrowserTab()) { ErrorLog.SuppressErrorLog = false; localizeHtmlPage(); getAdvancedOptionsSection().hidden = !userPreferences.advancedOptionsVisibleByDefault.value;