diff --git a/src/background/index.js b/src/background/index.js index e4da3a5..4de0862 100644 --- a/src/background/index.js +++ b/src/background/index.js @@ -44,7 +44,7 @@ import {loadStateFromStorage} from 'commerce/state/sync'; js: [ {file: 'extraction.bundle.js'}, ], - runAt: 'document_idle', + runAt: 'document_end', allFrames: true, }); diff --git a/src/extraction/index.js b/src/extraction/index.js index 2dfdfba..cdf7a4b 100644 --- a/src/extraction/index.js +++ b/src/extraction/index.js @@ -4,7 +4,8 @@ /** * Content script injected into tabs to attempt extracting information about a - * product from the webpage. + * product from the webpage. Set to run at "document_end" after the page has + * been parsed but before all resources have been loaded. */ import extractProductWithFathom from 'commerce/extraction/fathom'; @@ -20,15 +21,17 @@ async function attemptExtraction() { || extractProductWithFallback() ); - await browser.runtime.sendMessage({ - from: 'content', - subject: 'ready', - extractedProduct: { - ...extractedProduct, - url: document.location.href, - date: (new Date()).toISOString(), - }, - }); + if (extractedProduct) { + await browser.runtime.sendMessage({ + from: 'content', + subject: 'ready', + extractedProduct: { + ...extractedProduct, + url: document.location.href, + date: (new Date()).toISOString(), + }, + }); + } } (function main() { @@ -37,11 +40,10 @@ async function attemptExtraction() { const isInIframe = window !== window.top; const isBackgroundUpdate = window.location.hash === '#moz-commerce-background'; if (!isInIframe || isBackgroundUpdate) { - // Make sure the page has finished loading, as JS could alter the DOM. - if (document.readyState === 'complete') { + // Extract immediately, and again if the readyState changes. + attemptExtraction(); + document.addEventListener('readystatechange', () => { attemptExtraction(); - } else { - window.addEventListener('load', attemptExtraction); - } + }); } }());