[英]Chrome extension v3: content.js & background.js not communicating
我正在編寫一個 chrome 擴展 v3,其中內容腳本 (content.js) 偵聽表單提交事件並從表單獲取搜索輸入。 然后它向后台腳本(background.js)發送消息來執行搜索,並將搜索結果顯示在搜索結果容器中。 代碼如下
清單.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"]
}
]
}
內容.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);
});
});
});
背景.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 });
});
}
});
彈出窗口.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')
表明未從 background.js 收到 content.js 預期的結果
當我檢查控制台時,如果我將 console.log 放在 background.js 中,我沒有收到任何錯誤/消息
如果你想使用彈出到后台消息:
self.addEventListener
並正確使用chrome.runtime.onMessage
。content_scripts
,並將 content.js 重命名為 popup.js,因為它不是內容腳本。 內容腳本是在 web 頁面中運行的擴展腳本,而彈出窗口不是 web 頁面,而是帶有 chrome-extension:// URL 的擴展頁面。return true
(更多信息)將數據發送回彈出窗口,因為 chrome.tabs.sendMessage 不能與彈出窗口一起使用 - 它不在選項卡內運行,它是一個單獨的 window。PS 對於此任務,您不需要后台腳本:您可以在 popup.js 中執行所有操作,不需要消息傳遞或像 cheerio 這樣的庫(您可以使用內置的 DOMParser)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.