Reputation: 2111
I'm trying to grab the URL for every new page that is visited by the user. I found a SO answer that said to use content_scripts
so I put this in my manifest:
"permissions": [
"tabs"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["js/background.js"]
}
I also tried matches like this:
"matches": ["http://*/*", "https://*/*"],
And this is my background.js
file:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
alert(changeInfo.url);
});
chrome.tabs.onActivated.addListener(function(activeInfo) {
// how to fetch tab url using activeInfo.tabid
chrome.tabs.get(activeInfo.tabId, function(tab){
console.log(tab.url);
});
});
alert("BACON");
Nothing gets fired off after reloading the extension and then opening up new tabs and going to various websites. Could someone please help me figure out what I'm doing wrong? Thanks!
Upvotes: 1
Views: 314
Reputation: 15372
As per content scripts documentation:
Content scripts have some limitations. They cannot use chrome.* APIs, with the exception of:
- extension (getURL, inIncognitoContext, lastError, onRequest, sendRequest)
- i18n
- runtime (connect, getManifest, getURL, id, onConnect, onMessage, sendMessage)
- storage
Solution: in order to access chrome.tabs
API you should use a background page script.
Also note that according to chrome.tabs API documentation:
You can use most
chrome.tabs
methods and events without declaring any permissions in the extension's manifest file. However, if you require access to the url, title, or favIconUrl properties oftabs.Tab
, you must declare the"tabs"
permission in the manifest
manifest.json
...
"permissions": [
"tabs"
],
"background": {
"scripts": ["background.js"]
},
...
background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status==='loading' && changeInfo.url) {
alert(changeInfo.url);
}
});
Upvotes: 4