我正在尝试根据
docs将一些分析连接到我的 Chrome 扩展的
onStartup
事件中。但是,当通过浏览器中的图标打开扩展程序时,该事件似乎永远不会触发。
请注意,当安装、重新加载扩展等时,以下代码中的
onInstalled
事件会按预期触发。
chrome.runtime.onInstalled.addListener(function(details) {
console.log('Extension installed: ' + details.reason);
});
chrome.runtime.onStartup.addListener(function() {
console.log('Extension started');
});
注意,我正在运行 Chrome v37 -
onStartup
事件自 v23 起就可用。
您试图在打开弹出窗口时调用代码。这与“启动”扩展不同 -
chrome.runtime.onStartup
事件通常在每次浏览器启动时触发一次。
设置弹出页面时,chrome.browserAction.onClicked
事件不会触发;相反,您需要在弹出页面本身中执行一些代码(并且每次打开弹出窗口时都会执行该代码)。
您可以简单地从弹出页面本身发送分析事件。或者,如果您更喜欢从后台页面发送,您只需发消息。
我在manifest v3中写了一个chrome扩展,这是我的实验代码片段,它可以正确检测弹出窗口。
//popup.js
const isElementVisible = (ele, partiallyVisible = false) => {
const { top, left, bottom, right } = ele.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible ? ((top > 0 && top < innerHeight) ||
(bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) ||
(right > 0 && right < innerWidth)) : top >= 0 && left >= 0 &&
bottom <= innerHeight && right <= innerWidth;
};
let opened = false;
setInterval(function () {
let ele = document.getElementById("app");
if (isElementVisible(ele) && !opened) {
chrome.runtime.sendMessage({ type: "popup_window_opened" });
opened = true;
}
}, 1000);
//service_worker.js
chrome.runtime.onMessage.addListener(function (message, sender,
sendResponse) {
if (message.type == "popup_window_opened") {
console.log("popup window opened");
}
});
当我观察 Service Worker 的控制台输出时,我发现每次弹出窗口打开时,弹出窗口中的间隔计时器都会工作并向 Service Worker 发送消息,否则,弹出窗口中的间隔计时器将停止并且 Service Worker收不到任何消息。