I am trying to create a chromium extension that will find keywords located in the page source. They would appear as '"keywords": [these, are, keyword, examples, etc]'. I want to parse through the csv portion and have the results show up line by line in a popup or sidebar.
I've been stumbling my way through JavaScript using stackoverflow and ChatGPT. I can paste this script into the console and it will give the results I am looking for, but when I try it in my script nothing happens.
// contentScript.js
// Specify the keyword with a colon
const keyword = '"keywords":';
// Get the text content of the entire webpage
const pageText = document.body.innerText;
// Check if the keyword is present in the page text
const keywordIndex = pageText.indexOf(keyword);
if (keywordIndex !== -1) {
// Find the content within brackets following the keyword
const startIndex = pageText.indexOf('[', keywordIndex);
const endIndex = pageText.indexOf(']', keywordIndex);
if (startIndex !== -1 && endIndex !== -1 && startIndex < endIndex) {
const rawResults = pageText.substring(startIndex + 1, endIndex); // Remove the leading '['
const resultsArray = rawResults.split(',').map(value => value.trim().replace(/"/g, '')); // Split, trim, and remove quotations
// Send the results to the background script
chrome.runtime.sendMessage({ results: resultsArray });
} else {
console.log(`No results found following "${keyword}".`);
}
} else {
console.log(`"${keyword}" not found on the webpage.`);
}
I suggest that you should check the injection of
contentScriptto your pages as injecting it before the page is fully load might result in the losing of the content forcontentScriptto scan. Instructions for injecting the script after the page loaded can be found here