Chrome扩展:如何从新打开的窗口与Content.js通信?



我已经在chrome.action.onClicked.addListener中创建了如下所示的新窗口。

点击"检查"按钮在新打开的窗口,我需要连接到content.js和打印一些消息在窗口的控制台中。我不知道哪里出了问题!我使用Manifest版本3。

content.js

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {

if(msg.color === "#00FF00"){
document.body.style.backgroundColor = "green";
sendResponse({ status: "done" });
}
});

background.js

var urlRegex = /^(https?://)?[a-z0-9-]*.?[a-z0-9-]+.[a-z0-9-]+(/[^<>]*)?$/;
chrome.action.onClicked.addListener(function(tab) {
/*...check the URL of the active tab against our pattern and... */
if (urlRegex.test(tab.url)) {
/* ...if it matches, send a message specifying a callback too */
chrome.windows.create({
tabId: tab.id,
type:"popup",
url:"popup.html",
focused:true
});
}
});

popup.html

<html>
<head>
<script defer src="popup.js"></script>
</head>
<body>
<h3>Test Extension Page</h3>
<input type="button" id="sendMessage" value="Check"/>
</body>
</html>

popup.js

let sendMessageButton = document.getElementById("sendMessage");
console.log(document.URL);
console.log(sendMessageButton.value);
function getTitle()
{
return document.title;
}
sendMessageButton.onclick = function() {

chrome.tabs.query({ active: true, currentWindow: true }, function(tabs){
var tab = tabs[0];
chrome.scripting.executeScript(
{
target: {tabId:tab.id},
func: getTitle,
},
() => {
// This executes only after your content script executes
chrome.tabs.sendMessage(
tab.id,
{ color: "#00FF00" },
function (response) {
console.log(response.status);
}
);
});   
});  
};

新打开的窗口控制台错误。

Unchecked runtime.lastError: Cannot access contents of url "chrome-extension://jjaaoafdfmabdajdckiacompibnnmnlh/popup.html". Extension manifest must request permission to access this host.
Error handling response: TypeError: Cannot read properties of undefined (reading 'status') at chrome-extension://jjaaoafdfmabdajdckiacompibnnmnlh/popup.js:25:34

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

问题是你创建的窗口变得活跃,因此它成为chrome.tab .query在你的代码的结果,这意味着executeScript运行在你自己的扩展页,这不能工作,因为这个方法只适用于网站。

解决方案是将选项卡id作为URL参数传递。

//background.js

chrome.action.onClicked.addListener(tab => {
chrome.windows.create({
type: 'popup',
url: 'popup.html?' + new URLSearchParams({
tabId: tab.id,
title: tab.title,
}),
});
});

//popup.js

const params = new URLSearchParams(location.search);
const tabId = +params.get('tabId');
let title = params.get('title'); // initial title
document.getElementById('sendMessage').onclick = async function () {
title = (await chrome.tabs.get(tabId)).title;
let res = await chrome.tabs.sendMessage(tabId, { color: "#00FF00" });
};

最新更新