Chromium 扩展来解析页面源中的关键字

问题描述 投票:0回答:1

我正在尝试创建一个 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.`);
}
javascript web-scraping google-chrome-extension chrome-extension-manifest-v3 keyword-search
1个回答
0
投票

我建议您检查

contentScript
到页面的注入,因为在页面完全加载之前注入它可能会导致
contentScript
扫描的内容丢失。页面加载后注入脚本的说明可以在here

找到
© www.soinside.com 2019 - 2024. All rights reserved.