问题是如何在特定选项卡上查询此类事件:
目前,我研究过检查指定 URL 操作的最简单方法是使用内容脚本,它可以监听事件,然后使用消息 API 将结果发送到后台脚本。
最佳答案
您不能在特定选项卡上为此类事件注册监听器。可能有不同的方法,但我建议使用 chrome.tabs.* events 以监听有关所有选项卡的事件,然后手动进行过滤。
[ 备注 :您需要申请必要的 permissions 在您的 list 中,例如 "tabs" , "idle" , host match patterns ETC。]
User has loaded the tab with specific URL like: google.com
为以下事件附加监听器:
...然后根据 URL 进行过滤。例如。:
var urlRegex = /https?:\/\/([^\.]+\.)?google.com/;
chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
if (info.url && urlRegex.test(info.url)) {
/* The tab with ID `tabId` has been updated to a URL
* in the `google.com` domain. Let's do something... */
...
}
});
User has closed the tab.
为以下事件附加监听器:
...然后根据 URL 进行过滤。例如。:
var urlRegex = ...;
chrome.tabs.onRemoved.addListener(function(tabId, info) {
chrome.tabs.get(tabId, function(tab) {
if (urlRegex.test(tab.url)) {
/* The tab with ID `tabId`, with a web-page in the
* `google.com` domain, is being closed. Let's do something... */
...
}
});
});
The tab is inactive, like switching to another tab.
不幸的是,没有
onFocusLost
事件。您可以收听 chrome.tabs.onActivated 事件并跟踪每个窗口中的事件选项卡。然后,当另一个选项卡被激活时,如果先前激活的选项卡指向 google.com,请执行一些操作。 (我不会详细描述机制)。对于这种特殊情况,使用内容脚本和 可能更简单。 notify your background page 当标签停用时:
/* In `content.js` */
window.addEventListener("blur", function() {
chrome.runtime.sendMessage({ text: "focusLost" });
})
/* In `background.js` */
chrome.runtime.onMessage.addListener(function(msg, sender) {
if (msg.text === "focusLost") {
/* OMG - The user switched to another tab :( */
}
});
Check if the user is idle or not.
您无法检查用户是否在特定选项卡方面处于非事件状态,但一般情况下。正如您提到的,您可以使用 chrome.idle API,为 注册一个监听器chrome.idle.onStateChanged 事件。
chrome.idle.onStateChanged.addListener(function(newState) {
if (newState == "active") {
/* The user came back. Let's do something... */
} else {
/* The user is not around. Let's wait... */
}
});
关于javascript - 获取页面事件,标签关闭,失去焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19972322/