For some reason, I am not able to get the current tab when using devtools. Here is the code I am using:
chrome.tabs.query({currentWindow: true, active: true}, function(tabs)
This code always returns an empty array.
The code is running the background.js file, and the permissions are:
"permissions": [
"activeTab",
"tabs"
],
Iván Nokonoko comment is the answer.
Related
I thought this would be a regularly asked question, but I can not find the answer for it.
Is there a way for a chrome extension to have it's browser action popup available only on content_scripts matching pages?
Eg: I make an extension for a site. I want the popup to only be available when browsing the site (on the current tab). How do I do?
For me the browser action is always enabled by default, whatever page I'm browsing, and page action never enabled.
Thanks for your help
EDIT: Here is part of the manifest, I changed with pageAction with No success. I want my icon to activate only on tabs browsing LDLC.
{
"content_scripts": [
{
"js": [ "jquery.min.js", "scrooge.js" ],
"matches": [ "*://www.ldlc.com/fiche/*", "*://ldlc.com/fiche/*" ]
}],
"manifest_version": 2,
"permissions": [ "storage", "activeTab","*://ldlc.com/*", "*://scroogealpha.esy.es/*" ],
"page_action": {
"default_title": "Worth buying?", // optional; shown in tooltip
"default_popup": "popup.html" // optional
},
"web_accessible_resources": [
],
"background":{
"scripts" : ["eventPage.js"],
"persistent": false
}
}
Use a page action and in your background script listen for tab changes. When a tab url changes, check if you want to show the page action.
In your background script do something like this:
let matches = ["://www.ldlc.com/fiche/", "://ldlc.com/fiche/" ]
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
for (let i in matches) {
if (tab.url.includes(matches[i])) {
chrome.pageAction.show(tabId)
break
}
}
})
Also add the tabs permission in your manifest.
As a learning exercise I'm attempting to build an example Chrome extension that ensures sites on a 'greylist' are always opened in an incognito window.
Here's how far I have got - using the webNavigation.onBeforeNavigate event fired when a grey listed page is about to be navigated to I open a new tab in an incognito window, but now need to prevent the original tab from opening the page.
manifest.js:
"permissions": [
"webNavigation",
"tabs"
],
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
background.js:
chrome.webNavigation.onBeforeNavigate.addListener(function(details) {
chrome.tabs.get(details.tabId, function(tab) {
if(!tab.incognito) {
// Open the page in an incognito window
chrome.windows.create({ url: details.url, incognito: true});
// TODO stop non-incognito tab opening page!
}
});
}, {
url: [
{ hostEquals: 'badsite.com' }
],
});
To stop the navigation use window.stop() by injecting a content script in the tab:
chrome.tabs.executeScript(details.tabId, {code: 'window.stop()'});
Add a permission in manifest.json, otherwise you'll see an error in the background page console:
"permissions": [
"webNavigation",
"tabs",
"<all_urls>"
],
Partial answer arrived at from wOxxOm's input and further experiments and reading - to at least document what I found out.
manifest.js:
"permissions": [
"webNavigation",
"tabs",
"<all_urls>" // Note: Permission
],
...
background.js:
// Note: onCommitted
chrome.webNavigation.onCommitted.addListener(function(details) {
chrome.tabs.get(details.tabId, function(tab) {
if(!tab.incognito) {
// Stop non-incognito tab opening page
// Note runAt: "document_start"
chrome.tabs.executeScript(details.tabId, { runAt: "document_start", code: 'window.stop(); '})
// Open the page in an incognito window
chrome.windows.create({ url: details.url, incognito: true});
}
});
}, {
url: [
{ hostEquals: 'badsite.com' }
],
});
Listening for chrome.webNavigation.onCommitted events instead of onBeforeNavigate allows the script injected by chrome.tabs.executeScript to run when a grey listed page is navigated to from a new tab and a url is pasted into the omni box.
This prevents the grey listed page from being displayed, but the page is at least partially loaded. A history entry is not created but cookies or local storage items are created, so it does not meet the ultimate need of my original question.
two ways:
base on #wOxxOm
chrome.webNavigation.onBeforeNavigate.addListener((details) => {
chrome.tabs.executeScript(tabid,{code: 'window.stop()'});
});
not refresh
window.history.pushState(“object or string”, “Title”, “/new-url”);
We are new to chrome extensions - what we are trying to do is create an extension that can capture information from the current browser window. As an example, if we went to http://www.bbc.co.uk/sport/football/tables we would want to be able to pick out the teams name and details to be saved to our database for later use on our site.
Using jquery we initially added a button to the top of the page and when clicked, it would fire our jquery script and this worked fine but we would prefer to have an icon in the toolbar so when clicked we could navigate to the page and gather the info rather than adding a button to the page.
Manifest is set up like so:
{
"manifest_version": 2,
"name": "registration",
"version": "1",
"permissions": [
"http://*/*",
"https://*/*"
],
"content_scripts": [{
"matches": ["http://*/*"],
"js": ["jquery.min.js","app.js"]
}]
}
content_script
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getHTML")
sendResponse({data: document.getElementById('header').innerHTML});
else
sendResponse({}); // snub them.
});
Any pointers would really be appreciated.
Thanks
Rich
Im trying to load a url's favicon using chromes favicon url:
<img class='icon' src='chrome://favicon/yahoo.com' />
But im getting the error :
"Not allowed to load local resource: chrome://favicon/yahoo.com"
And in the manifest i have:
"permissions": [
"chrome://favicon/"
],
There isnt much available online about this topic. Any suggestions?
Problems in your code
"permissions": ["chrome://favicon/"], is an invalid pattern in manifest file
If you want to use the URL of the tab's favicon use chrome.tabs API in extension pages.
Demonstration
manifest.json
Registered background page and added necessary permissions.
{
"name": "Fav Icon",
"description": "http://stackoverflow.com/questions/14800881/not-allowed-to-load-local-resource-chrome-favicon",
"version": "1",
"manifest_version": 2,
"background": {
"scripts": [
"background.js"
]
},
"permissions": [
"tabs",
"<all_urls>"
]
}
background.js
chrome.tabs.query({
"active": true,//fetch active tabs
"currentWindow": true,//fetch tabs in current window
"status": "complete",//fetch completely loaded windows
"windowType": "normal"//fetch normal windows
}, function (tabs) {
for (tab in tabs) {
console.log(tabs[tab].favIconUrl);// Use this URL as needed
}
});
chrome.tabs.query will work in extension pages, if you want to use in content scripts use message passing to communicate URL.
References
chrome.tabs API
Message Passing
The URL needs to include the scheme as well:
<img src="chrome://favicon/http://www.yahoo.com">
Just ran into this issue and both
"permissions": ["chrome://favicon/"] and "permissions": ["chrome://favicon/*"]
worked as expected.
Chrome version 52.0.2743.116
Well, I know it's an old post but for those who are here to find this answer, why it is showing like this is basically because chrome://favicon/ and chrome://favicon/* both should be added in your mainfest.json
"permissions": ["chrome://favicon/", "chrome://favicon/*"]
NOTICE: mainfest v3 will have API dedicated to this but for now we don't have much blogs on that and also mainfest v2 will be no longer supported after 2023.
You can now use favicon as the permission with _favicon/?pageUrl=${url}&size=32 to load icons
Here is an example
Unfurtunely it will not work as it was in manifest v2. You have to use it differently.
Method 1 (lazy)
https://www.google.com/s2/favicons?domain=https://stackoverflow.com/
Method 2 (official)
manifest.json
"permissions": [
"favicon"
],
export const favicon = (pageUrl: string, size: number = 24) => {
const url = new URL(`chrome-extension://${chrome.runtime.id}/_favicon/`);
url.searchParams.append("pageUrl", pageUrl);
url.searchParams.append("size", size.toString());
return url.href;
};
favicon("https://stackoverflow.com/");
Additionaly add loading="lazy" attribute for you image, to prevent hundreds request.
I want to check some values in the content of chrome browser page when it completely loaded
like that
if(document.body.innerText.indexOf("Cat") !=-1)
Where and when can I make my check? please give me an clear example
I read some thing about "Background.html" and "Content script" but I can't do
Register a content script in the manifest file at "run_at": "document_idle" (which is the default) and put your code in the content script file. Then the script will be run when the page is ready.
If you want to detect from the background page whether a page is completely loaded, use the chrome.webNavigation.onCompleted event and do whatever you want, such as calling chrome.tabs.executeScript to execute a content script. This method could be useful over the previous method if the list of URLs is dynamic or if the URL patterns cannot be described using the match pattern syntax.
chrome.webNavigation.onCompleted.addListener(function(details) {
chrome.tabs.executeScript(details.tabId, {
code: ' if (document.body.innerText.indexOf("Cat") !=-1) {' +
' alert("Cat not found!");' +
' }'
});
}, {
url: [{
// Runs on example.com, example.net, but also example.foo.com
hostContains: '.example.'
}],
});
The webNavigation and host permissions have to be set in manifest.json, e.g.:
{
"name": "Test",
"version": "1.0",
"background": { "scripts": ["background.js"] },
"permissions": [ "webNavigation", "*://*/*" ],
"manifest_version": 2
}