I have created a Chrome extension that, as part of it's operation, opens a new tab with a specified url.
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "open_new_tab" ) {
chrome.tabs.create({"url": request.url});
}
}
);
(Full code available on GitHub)
This works fine on tabs with webpages, but I cannot get it to work on empty tabs, for example: chrome://apps/ To clarify, if I have a tab open and it is on stackoverflow.com, then when I click on my extension button it opens a new tab loading a generated url. When I am on a new tab, or a tab where the url begins with chrome:// then the extension does not work.
What permissions do I need to include to allow the extension to open in ANY tab? Including new tabs and any chrome:// tab?
Manifest.json:
{
"manifest_version": 2,
"name": "MyMiniCity Checker",
"short_name": "MyMiniCity Checker",
"description": "Checks what your city needs most and redirects the browser accordingly.",
"version": "0.2",
"author":"Richard Parnaby-King",
"homepage_url": "https://github.com/richard-parnaby-king/MyMiniCity-Checker/",
"icons": {
"128": "icon-big.png"
},
"options_page": "options/options.html",
"browser_action": {
"default_icon": "icon.png"
},
"permissions": ["tabs","storage","http://*.myminicity.com/","http://*/*", "https://*/*"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [ {
"matches": [ "http://*/*", "https://*/*"],
"js": [ "jquery-1.11.3.min.js" ]
}]
}
Background.js:
//When user clicks on button, run script
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, { file: "jquery-1.11.3.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "contentscript.js" });
});
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "open_new_tab" ) {
chrome.tabs.create({"url": request.url});
}
}
);
It appears as though the background.js file is not being executed. I suspect this to be a permissions. What permissions do I need in order to run this extension in every tab?
Well, this message is supposed to come from a content script you're trying to inject into the current tab.
The widest permission you can request is "<all_urls>", however, there are still URLs that are excluded from access.
You can only normally access http:, https:, file: and ftp: schemes.
file: scheme requires the user to manually approve the access in chrome://extensions/:
Chrome Web Store URLs are specifically blacklisted from access for security reasons. There is no override.
chrome:// URLs (also called WebUI) are excluded for security reasons. There is a manual override in the flags: chrome://flags/#extensions-on-chrome-urls, but you can never expect it to be there.
There is an exception to the above, chrome://favicon/ URLs are accessible if you declare the exact permission.
All in all, even with the widest permissions you cannot be sure you have access. Check for chrome.runtime.lastError in the callback of executeScript and fail gracefully.
As I was wanting this to run on EVERY page it meant I could not have the code in the content script. I moved all the code into the background script:
chrome.browserAction.onClicked.addListener(function(tab) {
//...
chrome.tabs.create({"url": newTabUrl});
//...
});
So when I click on my button the above code is called, using the enclosed jquery script.
Related
I have the following code in a background.js.
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.executeScript(tabId, {
file: 'inject.js'
});
} // if (changeInfo.status == 'complete') {
});
But when I change tabs the inject.js only runs in the active tab even if an inactive tab gets updated. In the inject.js I have an automated process running for a particular website and it's clicking through some pages looking for specific text. I want it to continue running on that one tab even if I open a new tab. But as soon as I change tabs the injection happens only on the active tab. I thought tab.tabId or tabId would be for the tab that was updated but it seems like it's always the active tab.
Is there a way to figure out what tab updated so I can pass the correct tabId to executeScript?
Here is what my manifest looks like:
{
"name": "Automated test",
"version": "0.0.1",
"manifest_version": 2,
"background": {
"scripts": [
"background.js"
],
"persistent": true
},
"browser_action": {
"default_title": "Test"
},
"permissions": [
"https://*/*",
"http://*/*",
"tabs",
"webNavigation"
]
}
So, #wOxxOm led me to what I needed. I did need a content-script and the reason why I think I wasn't seeing the results I was expecting is that I was failing to remove and re-add my extension. Sometimes it seems like it respects the changes made but maybe when you make changes to the manifest you need to remove and re-add the extension.
Once I did that it is correctly working on the inactive tab.
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
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
}