Chrome扩展v3:content.js和background.js未通信

72qzrwbm  于 2022-12-30  发布在  Go
关注(0)|答案(1)|浏览(596)

我正在编写一个chrome扩展v3,其中内容脚本(content.js)监听表单提交事件并从表单获取搜索输入,然后向后台脚本(background.js)发送消息以执行搜索,并在搜索结果容器中显示搜索结果。
manifest.json

{
  "manifest_version": 3,
  "name": "Get Free Copy",
  "description": "Searches for free copies of research papers on various websites",
  "version": "1.0",
  "permissions": ["declarativeNetRequest","tabs","webRequest", "webNavigation"],
  "host_permissions": ["https://*/*"],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_title": "Get Free Copy",
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["https://*/*"],
      "js": ["content.js"]
    }
  ]
}

content.js

// Listen for the form submission event
document.getElementById("search-form").addEventListener("submit", function(event) {
  event.preventDefault();

  // Get the search input
  var searchInput = document.getElementById("search-input").value;

  // Send a message to the background script to perform the search
  chrome.runtime.sendMessage({ type: "search", title: searchInput }, function(response) {
    // Clear the search results container
    document.getElementById("search-results").innerHTML = "";

    // Display the search results
    response.results.forEach(function(result) {
      var resultElement = document.createElement("a");
      resultElement.href = result.url;
      resultElement.textContent = result.title;
      document.getElementById("search-results").appendChild(resultElement);
    });
  });
});

background.js

// Handle the message event
self.addEventListener("message", (event) => {
  var request = event.data;
  if (request.type === "search") {
    // Perform the searches and send the results back to the content script
    var title = request.title;
    var title2 = title.replace(/ /g, "+"); // Replace spaces with +
    var results = [];
    var queries = [
      {
        url: `https://www.ncbi.nlm.nih.gov/pmc/?term=${title}`,
        title: "NCBI PMC"
      },
      {
        url: `https://www.biorxiv.org/search/${title}`,
        title: "bioRxiv"
      },
      {
        url: `https://www.medrxiv.org/search/${title}`,
        title: "medRxiv"
      },
      {
        url: `https://www.google.com/search?q=${title2}+filetype:pdf`,
        title: "PDF Search"
      }
    ];
    queries.forEach(function (query) {
      fetch(query.url)
        .then(function (response) {
          return response.text();
        })
        .then(function (html) {
          // Extract the relevant information from the HTML using cheerio or regular expressions
          var $ = cheerio.load(html);
          // ...
          results.push({
            title: query.title,
            url: query.url
            /* Extract other relevant information */
          });
        });
    });

    // Send the results back to the content script
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { results: results });
    });
  }
});

popup.html

<!DOCTYPE html>
<html>
<head>
  <title>Get Free Copy</title>
</head>
<body>
  <!-- Create a form for the search input -->
  <form id="search-form">
    <input type="text" id="search-input" placeholder="Enter the title of the research paper">
    <button type="submit">Search</button>
  </form>

  <!-- Create a container for the search results -->
  <div id="search-results"></div>

  <!-- Include the content script in the popup -->
  <script src="content.js"></script>
</body>
</html>

但是,我一直收到错误Error handling response: TypeError: Cannot read properties of undefined (reading 'results'),表明content.js所期望的结果没有从background.js收到
当我检查控制台时,如果我将console.log放入background.js中,我没有收到任何错误/或消息

z9zf31ra

z9zf31ra1#

如果要使用弹出到后台的消息:
1.删除self.addEventListener并使用chrome.runtime.onMessagecorrectly
1.从manifest.json中删除content_scripts,并将content.js重命名为popup.js,因为它不是一个内容脚本。内容脚本是在网页中运行的扩展脚本,而弹出窗口不是网页,它是一个带有chrome-extension:// URL的扩展页面。
1.使用sendResponse和return truemore info)将数据发送回弹出窗口,因为chrome.tabs.sendMessage不能与弹出窗口一起工作-它不在选项卡中运行,而是一个单独的窗口。
1.由于弹出窗口可能会在响应发送回之前关闭,您也可以将结果保存到chrome.storage,并在下次打开弹出窗口时显示。
P.S.对于此任务,您不需要后台脚本:您可以在popup.js中执行任何操作,而不需要消息传递或cheerio之类的库(您可以使用内置的DOMParser)。

相关问题