To fix the code you've provided, I'll address the issues mentioned in my previous response and modify the script accordingly. I'll add some comments to guide you through the changes.
document.addEventListener('DOMContentLoaded', () => {
const article = document.querySelector("article");
// `document.querySelector` may return null if the selector doesn't match anything.
if (article) {
const text = article.textContent || ''; // Ensure we have a string, even if textContent is null
const wordMatchRegExp = /\w+/g; // A simpler regular expression for matching words
// `match` instead of `matchAll` since we only need the count, not the matches themselves
const words = text.match(wordMatchRegExp) || []; // Avoid null by falling back to an empty array
const wordCount = words.length;
console.log(`Number of words: ${wordCount}`);
const readingTime = Math.round(wordCount / 200);
const helloMessage = document.createElement("p");
helloMessage.classList.add("color-secondary-text", "type--caption");
helloMessage.textContent = "Hello";
// Query for both elements regardless of their existence, we'll check later
const heading = article.querySelector("h1");
const dateParent = article.querySelector("time")?.parentNode;
// Decide where to insert the helloMessage based on what exists
const referenceNode = heading || dateParent;
if (referenceNode) {
referenceNode.insertAdjacentElement("afterend", helloMessage);
} else {
console.error('No h1 or time parent node found to insert hello message.');
}
} else {
console.error("No article found.");
}
});
Here's what was changed or added in the code:
- Wrapped the entire script in a
DOMContentLoaded event listener to ensure that the DOM is fully loaded when the script runs.
- Made the word match regular expression a bit simpler with
\w+, which matches word characters (letters, digits, and underscores).
- Used
match instead of matchAll to get the array of matches directly, without needing to use Array.from or spread syntax.
- Ensured
text.match(wordMatchRegExp) falls back to an empty array in case there are no matches to avoid a potential null value causing an error.
- Introduced error logs (
console.error) to help with debugging if elements are not found.
Remember that this script should be placed in a content script within your Chrome extension. The browser will execute this content script on the pages you have specified in your manifest.json. Make sure that you've set the correct permissions and matches for URLs where you intend the extension to run. Here's how your manifest.json might look like in the case of a v3 extension:
{
"manifest_version": 3,
"name": "Your Extension Name",
"version": "1.0",
"permissions": ["activeTab"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["your_script.js"],
"run_at": "document_idle"
}
],
// ... other necessary fields like icons, description, etc.
}
Make sure to replace your_script.js with the path to the actual JavaScript file containing your fixed code.