您无法在特定选项卡上注册此类事件的侦听器。有不同的方法可能,但我建议使用chrome.tabs.* http://developer.chrome.com/extensions/tabs.htmlevents 用于侦听有关所有选项卡的事件,然后手动进行过滤。
[Note:您需要请求必要的权限 http://developer.chrome.com/extensions/declare_permissions.html在你的清单中,例如"tabs" http://developer.chrome.com/extensions/declare_permissions.html#tabs, "idle" http://developer.chrome.com/extensions/declare_permissions.html#idle, the 主机匹配模式 http://developer.chrome.com/extensions/declare_permissions.html#host-permissions etc.]
用户已加载具有特定 URL 的选项卡,例如:谷歌网站
附加以下事件的侦听器:
- chrome.tabs.onCreated http://developer.chrome.com/extensions/tabs.html#event-onCreated
- chrome.tabs.on更新 http://developer.chrome.com/extensions/tabs.html#event-onUpdated
...然后根据 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... */
...
}
});
用户已关闭该选项卡。
附加以下事件的侦听器:
- chrome.tabs.onRemoved http://developer.chrome.com/extensions/tabs.html#event-onRemoved
...然后根据 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... */
...
}
});
});
该选项卡处于非活动状态,就像切换到另一个选项卡一样。
不幸的是,这儿没有onFocusLost
事件。你可以听听chrome.tabs.onActivated http://developer.chrome.com/extensions/tabs.html#event-onActivated事件并跟踪每个窗口中的活动选项卡。然后,当激活另一个选项卡时,如果先前激活的选项卡指向,则执行某些操作谷歌网站。 (我不会详细描述机制)。
对于这种特殊情况,使用内容脚本可能会更简单通知您的后台页面 http://developer.chrome.com/extensions/messaging.html#simple当选项卡停用时:
/* 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 :( */
}
});
检查用户是否空闲。
您无法检查用户是否在特定选项卡上处于非活动状态,但一般而言。正如您提到的,您可以使用铬.空闲API,注册一个监听器chrome.idle.onStateChanged http://developer.chrome.com/extensions/idle.html#event-onStateChanged event.
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... */
}
});