Reputation: 39
I have a callback function that should search all tabs for a given URL, navigate to that tab if it's open and if it is not open it should open it.
I have the following query checking the tabs for the url
chrome.tabs.query({url: destination}, function (result) {
//If it found no results then the page is not open
if(result == null) {
console.log(destination + " not found in tabs. Function will open Tab.")
//Appropriate function...
}
//If it's open, the function will switch to the tab instead.
else {
//Use the tab ID of the first result
var tabID = result[0].id;
//Appropriate function using id to open tab
}
The problem is that result is always null or undefined, and never returns an array (Even when destination == "http://*/*") I originally had if (result.length == 0) but it would give errors relating to the type
I've also tried using
chrome.tabs.update(tabID, {
selected: true
});
to switch to the tab but this doesn't work. I thought it may be because I would need to place this in the background.js page, but I was unable to call it from this page.
chrome.extension.getBackgroundPage().myFunction();
does not work.
EDIT:
You mentioned permission causing an empty string. This is probably the answer, but I do have tabs set in permissions. These are my permissions in my manifest:
"permissions": [
"storage",
"notifications",
"activeTab",
"tabs",
"bookmarks",
"browsingData",
"identity",
"topSites",
"history"
]
Upvotes: 1
Views: 2367
Reputation: 212
This is essentially a question about chrome.tabs.query.
This method takes an object as the first argument. A property called "url" can be set to a string using one of the following patterns. The result will be an array containing all tabs with urls matching the pattern.
NOTE: Unless you have specified the "tabs" permission in your manifest, or a domain matching the returned url value, the url property of any returned TabObjects will be an empty string.
Example queries:
*://*/* will return all tabs
http://*/* will return all tabs with the http protocol
http://www.google.com/* will return all tabs with the http protocol and the domain www.google.com
While these patterns may remind you of regular expressions, they are not the same. The last asterisk in this query always means 0+ occurrences.
Note, you cannot use the pattern *://*.google.com/* to search all subdomains of google.com.
I will also note here that you can give an array of patterns for the url property to search.
Here is an example:
chrome.tabs.query( { "url":[
"*://music.google.com/*", // copy this from manifest.json is better idea
"*://video.google.com/*"
] }, function( tabs ){
if( tabs.length ){ /* tabs[ 0 ].url is blank depending on permissions */ }
} )
Upvotes: 2