[英]OnActivated is only working when new tab opened
I'm trying to communicate with the content script of the tab that has just been switched to using message passing. 我正在尝试与刚刚切换为使用消息传递的选项卡的内容脚本进行通信。 Here is my code in the background.js script.
这是我在background.js脚本中的代码。
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.sendMessage(activeInfo.tabId, { greeting: "hello" }, function(response) {
console.log(response.farewell);
});
});
And here is my code in my content script: 这是内容脚本中的代码:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
sendResponse({ farewell: "goodbye" });
loadContent();
});
Is the content script no longer listening in an inactive tab even when it's switched back to that tab? 即使将内容脚本切换回该选项卡,它也不再在非活动选项卡中监听吗? Why does this only run in a newly opened tab?
为什么只在新打开的选项卡中运行?
To further clarify why I want to do this, sometimes tabs are left open without reloading, and my script has already been executed. 为了进一步阐明为什么要执行此操作,有时会在不重新加载的情况下将选项卡保持打开状态,并且我的脚本已经执行。 When information pertaining to the script changes using the popup options, I want the content to reload on tab change, and a particular function to run again without reloading the page.
当使用弹出选项更改与脚本有关的信息时,我希望在选项卡更改时重新加载内容,并希望特定功能再次运行而无需重新加载页面。 Therefore, injecting the content script is less than ideal since it's already been executed.
因此,注入内容脚本不是很理想,因为它已经执行了。
Try this : 尝试这个 :
background.js background.js
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
chrome.tabs.sendMessage(activeInfo.tabId,
{ greeting: "hello" }, function(response) {
console.log(response.farewell);
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.