It's not possible to register a listener for events on a specific tab directly. However, you can use chrome.tabs.* events to listen for events on all tabs and then filter them manually.
[Note: Make sure to request the necessary permissions in your manifest file, such as "tabs", "idle", or host match patterns.]
User has loaded a tab with a specific URL like: google.com
Add listeners for the following events:
...and then filter based on the URL. For example:
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. Take appropriate action... */
...
}
});
User has closed the tab.
Add listeners for the following events:
...and then filter based on the URL. For instance:
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` containing a web-page in the
* `google.com` domain is being closed. Perform actions accordingly... */
...
}
});
});
The tab becomes inactive, such as when switching to another tab.
Although there isn't an onFocusLost
event, you can listen for the chrome.tabs.onActivated event and track the active tab in each window. Then take action if the previously active tab was on google.com. Alternatively, consider using a content script to notify your background page when the tab is deactivated:
/* 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") {
/* User switched to another tab :( */
}
});
Check if the user is idle or not.
You can't check if the user is inactive specifically on a tab, but overall. You mentioned using the chrome.idle API and listening for the chrome.idle.onStateChanged event for this purpose.
chrome.idle.onStateChanged.addListener(function(newState) {
if (newState == "active") {
/* User is back. Take action... */
} else {
/* User is idle. Wait for activity... */
}
});