Skip to content
This repository has been archived by the owner on Dec 3, 2020. It is now read-only.

Commit

Permalink
Fix #29: Attempt extraction after parsing is finished, before loading.
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Kelly committed Oct 2, 2018
1 parent 67f3ad6 commit f8ed9d3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
2 changes: 1 addition & 1 deletion src/background/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import {loadStateFromStorage} from 'commerce/state/sync';
js: [
{file: 'extraction.bundle.js'},
],
runAt: 'document_idle',
runAt: 'document_end',
allFrames: true,
});

Expand Down
32 changes: 17 additions & 15 deletions src/extraction/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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() {
Expand All @@ -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);
}
});
}());

0 comments on commit f8ed9d3

Please sign in to comment.