我正在尝试创建一个 chromium 扩展,它将查找位于页面源中的关键字。它们将显示为““关键字”:[这些、是、关键字、示例等]”。我想解析 csv 部分,并在弹出窗口或侧边栏中逐行显示结果。
我一直在使用 stackoverflow 和 ChatGPT 尝试 JavaScript。我可以将此脚本粘贴到控制台中,它会给出我正在寻找的结果,但是当我在脚本中尝试它时,什么也没有发生。
// 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.`);
}