From 406a7cd4c0efea2efdfd9763ad203947c6bf54c1 Mon Sep 17 00:00:00 2001 From: tophf Date: Thu, 9 Aug 2018 20:33:04 +0300 Subject: [PATCH] FF bug workaround: apply styles to more iframes --- background/background.js | 26 ++++++++++++++++++++++++++ content/apply.js | 24 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/background/background.js b/background/background.js index a0ae97fe..80f3f13a 100644 --- a/background/background.js +++ b/background/background.js @@ -56,6 +56,32 @@ var browserCommands, contextMenus; // register all listeners chrome.runtime.onMessage.addListener(onRuntimeMessage); +if (FIREFOX) { + // see notes in apply.js for getStylesFallback + const MSG_GET_STYLES = 'getStyles:'; + const MSG_GET_STYLES_LEN = MSG_GET_STYLES.length; + chrome.runtime.onConnect.addListener(port => { + if (!port.name.startsWith(MSG_GET_STYLES)) return; + const tabId = port.sender.tab.id; + const frameId = port.sender.frameId; + const options = tryJSONparse(port.name.slice(MSG_GET_STYLES_LEN)); + port.disconnect(); + getStyles(options).then(styles => { + if (!styles.length) return; + chrome.tabs.executeScript(tabId, { + code: ` + applyOnMessage({ + method: 'styleApply', + styles: ${JSON.stringify(styles)}, + }) + `, + runAt: 'document_start', + frameId, + }); + }); + }); +} + { const listener = URLS.chromeProtectsNTP diff --git a/content/apply.js b/content/apply.js index 109b6713..addd5d17 100644 --- a/content/apply.js +++ b/content/apply.js @@ -50,11 +50,35 @@ // On own pages we request the styles directly to minimize delay and flicker if (typeof API === 'function') { API.getStyles(request).then(callback); + } else if (!CHROME && getStylesFallback(request)) { + // NOP } else { chrome.runtime.sendMessage(request, callback); } } + /** + * TODO: remove when FF fixes the bug. + * Firefox borks sendMessage in same-origin iframes that have 'src' with a real path on the site. + * We implement a workaround for the initial styleApply case only. + * Everything else (like toggling of styles) is still buggy. + * @param {Object} msg + * @param {Function} callback + * @returns {Boolean|undefined} + */ + function getStylesFallback(msg) { + if (window !== parent && + location.href !== 'about:blank') { + try { + if (parent.location.origin === location.origin && + parent.location.href !== location.href) { + chrome.runtime.connect({name: 'getStyles:' + JSON.stringify(msg)}); + return true; + } + } catch (e) {} + } + } + function applyOnMessage(request, sender, sendResponse) { if (request.styles === 'DIY') { // Do-It-Yourself tells our built-in pages to fetch the styles directly