From f8ed9d30870a4348fb70035cd4b903e75ad2422f Mon Sep 17 00:00:00 2001 From: Michael Kelly Date: Mon, 1 Oct 2018 11:40:25 -0700 Subject: [PATCH] Fix #29: Attempt extraction after parsing is finished, before loading. --- src/background/index.js | 2 +- src/extraction/index.js | 32 +++++++++++++++++--------------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/src/background/index.js b/src/background/index.js index 94391eb..8cfae69 100644 --- a/src/background/index.js +++ b/src/background/index.js @@ -55,7 +55,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 c57e0a8..1391a9a 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 config from 'commerce/config/content'; @@ -21,15 +22,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(), + }, + }); + } } (async function main() { @@ -51,10 +54,9 @@ async function attemptExtraction() { return; } - // 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); - } + }); }());