The question is how to query such events on specific tab:
Currently as far I have researched the easiest way to check the specify URL actions is to use content scripts, which can listen for events and then send the results with message API to background script.
You cannot register a listener for such events on a specific tab. There are different approaches possible, but I suggest using chrome.tabs.* events to listen for events regarding all tabs and then do the filtering manually.
[Note: You will need to request the necessary permissions in your manifest, e.g. "tabs", "idle", the host match patterns etc.]
User has loaded the tab with specific URL like: google.com
Attach listeners for the followig events:
...and then filter based on the URL. E.g.:
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.
Attach listeners for the followig events:
...and then filter based on the URL. E.g.:
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.
Unfortunately, there is no onFocusLost
event. You could listen for the chrome.tabs.onActivated event and keep track of the active tab in each window. Then when another tab is activated, do something if the previously activated was pointing to google.com. (I am not going to describe a mechanism in detail).
For this particular case, it might be simpler to use a content script and 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") {
/* OMG - The user switched to another tab :( */
}
});
Check if the user is idle or not.
You cannot check if the user is inactive in regard of a specific tab, but in general. As you mentioned you can use the chrome.idle API, registering a listener for the chrome.idle.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... */
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With