我只是将此消息从background
发送到contentScript
,内容应该侦听此消息并执行函数。
我的contentScript.js:
function clickButton() {
const sendButton = document.querySelector('span[data-testid="send"]');
if (sendButton) {
console.log("Button Clicked");
sendButton.click();
// Communicate back to the background script or popup
chrome.runtime.sendMessage({ action: "buttonClicked" });
}
}
// Execute the clickButton function when a message is received
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action === "clickButton") {
console.log("Content Script HIT") ;
clickButton();
}
});
background.js:
chrome.tabs.create({ url: url }, function (tab){
chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
if (tabId === tab.id && changeInfo.status === "complete") {
console.log('TAB CREATED') ;
chrome.tabs.sendMessage(tab.id, { action: "clickButton" }, function (response) {
console.log('Response from ContentScript', response);
sendResponse({ success: true });
});
}
});
})
官方的chrome文档似乎也没有比我已经做的更有帮助https://developer.chrome.com/docs/extensions/mv3/messaging/
1条答案
按热度按时间z2acfund1#
让我来回答那些为同一个问题而挣扎的人:
问题是我的***manifest.json***,我缺少以下字段。表示您的***contentScript.js***应该在哪个主机/平台上执行:
]
此外,要在所有网页上执行contentScript,您可以用途: