Checking tab status in a chrome extension with a popup without the tabs permission - google-chrome

I'm currently trying to build my first chrome extension and I only need it to interact with pages of a few domains, so I want to avoid using the "tabs" permission since I understand it would have me request access to all information and all domains.
Instead I want to restrict myself to using the aciveTab permission and, if need be, a content script.
In short, what I want to do is display a "Subscribe button" in my extension's popup if the currently selected tab's url is of the domain(s) I'm interested in.
I can get the url of the page when it's created using a content script but I don't know how to make sure the user is still on that page when my extension is clicked.
I haven't managed to get anything done with activeTab.
Thanks in advance for any piece of advice you can give, I'll check on the answers (if any) after work.

A working example with the activeTab permisison:
In your popup.js
chrome.tabs.query({lastFocusedWindow: true, active: true}, function(tabs) {
if (tabs && tabs[0] && tabs[0].url) {
var match = tabs[0].url.match(/^[^:]+:\/\/([^\/]+)/);
if (match) {
var domain = match[1];
if (domain == 'stackoverflow.com')
alert('test');
}
}
});
Note:
You have to declare the "activeTab" permission in your manifest (of course).
JavaScript code must be in a standalone file and included in popup.html with <script src="..."></script>. Inline JavaScript is not allowed due to CSP.

Related

Inject HTML signature into Gmail from hosted page

I have the basic shell of a Chrome extension done and have come to the point where I am trying to inject an HTML signature into Gmail using code hosted on an unindexed page on my site. The reason I want to do this is to be able to include web fonts, something that for the life me I can't figure out why Gmail hasn't allowed you to do from their font library.
In any regard, as I said, I have a right-click context menu option ready to trigger a script from my js function page and the extension loads without errors. I need to figure out the best way to inject the HTML into the email and without losing any of the formatting that has been done on the page.
I have created the extension manifest, set the permissions on the context menu and created a function to call back to the js page that will inject the signature.
var contextMenus = {};
contextMenus.createSignature =
chrome.contextMenus.create(
{"title": "Inject Signature",
"contexts": ["editable"]},
function (){
if(chrome.runtime.lastError){
console.error(chrome.runtime.lastError.message);
}
}
);
chrome.contextMenus.onClicked.addListener(contextMenuHandler);
function contextMenuHandler(info, tab){
if(info.menuItemId===contextMenus.createSignature){
chrome.tabs.executeScript({
file: 'js/signature.js'
});
}
}
The end result is nothing enters the page and get massive errors related to cross-site because the domain is not the same obviously. This has obviously been solved as there are numerous signature extensions out there. I would probably use one of theirs but a) I want to build it on my own, b) they all want you to use their templates, none of them that I have seen will let you just use your own code.
So, any ideas?

Chrome Extension Content Script on https://chrome.google.com/webstore/

Is Chrome blocking access to the webstore url?
I would like to make an extension that displays a like button beside the +1 button, but it looks like that content scripts are not working on https://chrome.google.com/webstore/*
Is that true?
TL;DR The webstore cannot be scripted by extensions, and the flag that previously allowed you to do that (--allow-scripting-gallery) has been removed in Chrome 35.
Chrome extensions cannot execute Content scripts / insert CSS the Chrome Web Store. This is explicitly defined in the source code, at function IsScriptableURL (click on the previous link to see the full logic).
// The gallery is special-cased as a restricted URL for scripting to prevent
// access to special JS bindings we expose to the gallery (and avoid things
// like extensions removing the "report abuse" link).
// TODO(erikkay): This seems like the wrong test. Shouldn't we we testing
// against the store app extent?
GURL store_url(extension_urls::GetWebstoreLaunchURL());
if (url.host() == store_url.host()) {
if (error)
*error = manifest_errors::kCannotScriptGallery;
return false;
}
manifest_errors::kCannotScriptGallery is defined here:
const char kCannotScriptGallery[] =
"The extensions gallery cannot be scripted.";
The error can be viewed in the background page's console when you use chrome.tabs.executeScript to inject a script in a Web Store tab. For instance, open https://chrome.google.com/webstore/, then execute the following script in the background page of an extension (via the console, for live debugging):
chrome.tabs.query({url:'https://chrome.google.com/webstore/*'}, function(result) {
if (result.length) chrome.tabs.executeScript(result[0].id, {code:'alert(0)'});
});

Communicating with content scripts without requesting "tabs" permission

When developing a Chrome extension, my background script needs to communicate with the content scripts in the tabs loaded with a particular site.
Is there a way to communicate without using chrome.tabs.sendRequest?
This function requires the "tabs" permission which shows up as "this extension has access to your browsing history," which scares off users.
Sorry, there is no other way around.
UPDATE
Actually there is a way. Instead of pushing data from a background page to a content script you can pull data from a content script, and this doesn't require any permissions:
content script:
chrome.extension.sendRequest({cmd: "getData"}, function(response) {
console.log("data:", response);
});
background page:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.cmd == "getData") {
sendResponse({param1: "value1", param2: "value2"});
}
});
Remember even if you could communicate with background page without using chrome.tabs.sendRequest (actually it is almost impossible), you still need the tabs permission in order to inject a content script.
Read more: http://code.google.com/chrome/extensions/content_scripts.html

Could I make a Google Chrome extension for chrome pages (downloads, extensions etc)?

I'd like to make a very simple extensions that slightly alters how the Downloads page looks. Changing the History page might be interesting too, but that's for later.
Is there a way to do that?
I tried making a Content Script extension, with "chrome://downloads" as match in manifest.json. Chrome won't allow that and responds with an error when packaging the extension.
Is there another simple way? It has to be simple, because changes would be simple, because all chrome:// pages are built with HTML, JS and CSS.
edit
After trying with background scripts a little...
I can't get chrome.tabs.executeScript to work! I added in background.html:
chrome.browserAction.onClicked.addListener(function(tab) {
alert(this.document.body.innerHTML);
alert(chrome.tabs.executeScript(null, {
code : "document.body.style.backgroundColor = 'red';"
}));
});
And I added this in manifest.json to add a (invisible) 'browser action button':
,"browser_action": {
/* "popup": "background.html",*/
"name": "Alter page"
}
The onClicked event fires both alerts (first is background.html's body, second is undefined). But the code (a string with document.body.style.backgroundColor = 'red';) doesn't execute! And ofcourse there's no debugging for extensions like this =)
Any tips anyone? I'm trying to get a hold of the tab's window.document (not background.html's window.document!). An injected script (that's what chrome.tabs.executeScript is supposed to do) should do that.
PS
I'm stealing from make_page_red/manifest and make_page_red/background.html
The 'extension' I have so far: http://hotblocks.nl/js/downloads.rar
EDIT
I found out what I want to achieve is possible with just CSS. I don't need to inject javascript. Does that make it easier? Does that make it possible? =)
According to this documentation, chrome:// URLs are an invalid scheme so they won't be matched:
A match pattern is essentially a URL that begins with a permitted scheme (http, https, file, or ftp), and that can contain '*' characters.
I would look into using override pages instead.
As requested, here's my extension that can at least load when chrome://downloads is loaded, although as I said, I don't think you can modify the page even if you know that's the page you're viewing.
manifest.json
{
"name": "Test",
"version": "0.0.1",
"background_page": "background.html",
"permissions": [
"tabs"
]
}
background.html
<script>
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab)
{
if (tab.status == "complete")
{
alert(tab.url);
// should alert 'chrome://downloads' on that page. You can
// check for this url here and then do whatever you want
}
});
</script>
Update: Since Chrome 31 there is an API for extensions that allows access to Chrome's downloads: https://developer.chrome.com/extensions/downloads
There's also an API that allows access to list and manage other installed extensions: https://developer.chrome.com/extensions/management
(Previous Answer)
Unfortunately, there's not currently an API for Chrome extensions to access information about a user's downloads. It's a widely requested feature, though, and there's some discussion among Chrome developers here: http://code.google.com/p/chromium/issues/detail?id=12133
Star the issue if it's a feature that you'd like to see, and you'll receive email updates.
As this page shows, there is no API to override the downloads page... However, there is a way to make a file you have made replace the chrome://downloads/ page whenever it is loaded using javascript in your background page...
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(changeInfo.status === "loading"){
if(tab.url === "chrome://downloads/"){
chrome.tabs.update(tab.id, {url: "REPLACEMENT.html"});
}
}
});
Essentially what this does is - As soon as the page chrome://downloads begins loading (using the tabs.onUpdated API), the page is redirected to REPLACEMENT.html (Using tabs.update API)... There is no visible delay in the tab update
as this script is run before the chrome://downloads page begins loading... You can use a similar code in your file by pressing CTRL + U on the downloads page to view and copy its source code

HTML5 Local Storage, how to pass variables?

Ok, here is my problem. I am writing a Chrome extension, it's almost done, but the problem is, for example:
[Page popup.html]
localStorage["code"] = "alert('Hello!');";
[File injection.js; which will be called everytime a page is loaded, content script I think]
localStorage["code"] = (localStorage["code"] != undefined) ? localStorage["code"] : "alert('Default!');";
eval(localStorage["code"]);
I have tried 2 methods, the first thing is to NOT OPEN THE POP UP, so that every page I load would run command alert("Default!"); and it works. Then I tried to load the popup first, and I realize that the variable localStorage["code"] is now up to the page I load, not to my extenstion anymore. In a quick explanation, in my extension, localStorage["code"] == "alert('Hello');"; but in http://google.com localStorage["code"] == ""; or in http://facebook.com localStorage["code"] == "";.
My question is, is there anyway to store localStorage["code"] from popup.html that injection.js can access?
Three are 2 kinds of local storages - one belongs to extension itself (can be accessed only from a background page, popup page or any page bundled into extension package), another one belongs to the site (can be accessed only from a content script).
So if you need to access local storage value that was set in a popup from a content script, you need to send a request to a background page, read the value there, and send it back to a content script. How to do that is explained in Message Passing doc.
Check this out :
Content-Script :
chrome.extension.sendRequest({ action : "getCode" }, function(response) {
alert(response.getCode);
});
Background Page :
chrome.extension.onRequest.addListener(function(request, sender, sendResponse)
{
case "getCode":
sendResponse({ getCode: localStorage['code'] });
break;
}