![](/img/trans.png)
[英]Passing array (of objects) from popup.js to content.js in chrome extension
[英]Unable to send message from popup.js to content.js in chrome extension
我一直在構建擴展並嘗試在單擊彈出窗口中的按鈕時向內容腳本發送消息,但一直收到此錯誤“無法建立連接。接收端不存在。” 有時還會在 popup.js 中出現“Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')”
// 清單.json 文件
{
"manifest_version": 3,
"name": "Extension",
"version": "1.0",
"action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"js": ["content.js"],
"matches": ["https://discord.com/channels/*"]
}
],
"permissions": ["tabs"],
"background": {
"service_worker": "background.js"
},
"host_permissions": ["https://discord.com/channels/*"]
}
// popup.js 文件。
const sendMessageBtn = document.querySelector("button");
sendMessageBtn.addEventListener("click", async () => {
console.log("clicked"); // being logged to console
const [tab] = await chrome.tabs.query({
active: true,
lastFocusedWindow: true,
});
const response = await chrome.tabs.sendMessage(tab.id, { greeting: "hello" });
// do something with response here, not outside the function
console.log(response);
});
單擊按鈕時出現錯誤:“無法建立連接。接收端不存在。” 在擴展錯誤日志中
// content.js 文件
console.log("content script running"); // being logged to console
chrome.runtime.onMessage.addListener(
async function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
// console.log(request);
if (request.greeting === "hello")
await sendResponse({farewell: "goodbye"});
}
);
//彈出.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Extension</title>
<link rel="stylesheet" href="popup.css" />
</head>
<body>
<h1>extension</h1>
<input id="message-field" type="text" placeholder="enter message" />
<button>Send message</button>
<script src="popup.js"></script>
</body>
</html>
有幾個問題。
當彈出窗口的開發工具集中時,Chrome 中的一個錯誤會破壞 chrome.tabs.query,更多信息。
chrome.runtime.onMessage 偵聽器無法在 Chrome 中使用async
聲明,更多信息。
安裝/更新擴展時,其新內容腳本不會自動注入到 Chrome/ium 中當前打開的選項卡中,因此您必須自己明確地執行此操作,如此處所示,但在以下情況下有更好的選擇你的,只有在用戶調用擴展后才需要訪問頁面:通過 executeScript 進行編程注入。
content_scripts
document.querySelector('button').onclick = async () => {
// workaround for devtools window https://crbug.com/462939
const { id: windowId } = await chrome.windows.getCurrent();
const [tab] = await chrome.tabs.query({ active: true, windowId });
let result;
try {
[{ result }] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
// this runs in the web page, so it can't see variables in scope like `tab`
func: (param1, param2) => {
return document.documentElement.innerHTML;
// return {it: 'can', be: ['an object', 'too']};
},
// this is sent to the func's param1 and 2
args: [123, { foo: 'bar' }],
});
} catch (err) {
// the tab is not injectable
console.warn(err);
return;
}
console.log(result); // printing in the popup's devtools console
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.