How can I go about redirecting chrome in an extension when visiting a given URL?
For example: when I visit http://yahoo.com/ I want it to redirect to http://google.com/
NOTE: A former version of this question asked whether there is any Google chrome extension which automatically redirects the tab when it visits a certain URL. Accordingly, the (currently two) answers below address different questions.
There are many options, the one more convoluted than the other.
The webRequest API, specifically the onBeforeRequest event. (Even better, the upcoming declarativeWebRequest API).
Content scripts. Inject location.replace('http://example.com') in a page.
The tabs API. Use the onUpdated event to detect when a page has changed its location, and chrome.tabs.update to change its URL. Avoid an infinite loop though!
The first one is the best one, because it is activated before a page is even requested. The second one can be activated after the request has been fulfilled, but before the page is rendered ("run_at":"document_start") or after it's rendered ("run_at":"document_end"). I mentioned the last one for completeness, but you shouldn't use it, because the other options are way better.
Here's an example using the webRequest API, a simple extension which allows me to browse pages on the Pirate bay, even though the main hosts are taken down by my ISP (the actual list of URLs is much longer, but I have omitted them for the sake of the example).
See match patterns for an explanation on the URL formats.
manifest.json
{
"name": "The Pirate Bay",
"description": "Redirect The Pirate Bay to a different host",
"version": "1.0",
"manifest_version": 2,
"background": {"scripts":["background.js"]},
"permissions": [
"webRequest",
"*://thepiratebay.se/*",
"*://www.thepiratebay.se/*",
"webRequestBlocking"
]
}
background.js
var host = "http://tpb.pirateparty.org.uk";
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return {redirectUrl: host + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1]};
},
{
urls: [
"*://piratebay.se/*",
"*://www.piratebay.se/*"
],
types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
},
["blocking"]
);
I know I am a bit late in the game to answer this question Still I would like to answer this for future readers. Have a look at
Requestly - A Chrome Extension to modify Network Requests.
Currently, You can setup rules for
Redirect a request URL to another url.
Block some requests.
Replace some part in URL with another string
Modify Headers (Add/Remove/Modify Request and Response Headers)
Screenshots for more understanding:
List of Rules
Rule Type Cards
New Redirect Rule
Headers Modification Rule
There are lot of things in roadmap to be covered in requestly like
Switching User Agents
.. and a lot more.
PS: I have created this So you can blame me if you do not find this helpful :)
You could use my extension. Go to "Rewrite Rules" tab, click the "+" button and add a new rewrite rule. Note that the rewrite rule is actually an RegEx so characters like / must be escaped
https://chrome.google.com/webstore/detail/dev-helper/kbbgddcndpjnadfacanamniaomcohlcc?hl=en
Related
I ran into some trouble when upgrading to manifest v3, and would greatly appreciate your help and input.
Background:
Using manifest v3
Using ShowAction() instead of ShowPageAction() which is deprecated
Used to work with manifest v2 and ShowPageAction()
Already read this post which did not apply to manifest v3 (or seemed like it didn't apply)
Also followed this google guide for upgrading from ShowPageAction to ShowAction
After following chrome's tutorial, which is reposted below:
// background.js
// Wrap in an onInstalled callback in order to avoid unnecessary work
// every time the background script is run
chrome.runtime.onInstalled.addListener(() => {
// Page actions are disabled by default and enabled on select tabs
chrome.action.disable();
// Clear all rules to ensure only our expected rules are set
chrome.declarativeContent.onPageChanged.removeRules(undefined, () => {
// Declare a rule to enable the action on example.com pages
let exampleRule = {
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {hostSuffix: '.example.com'},
})
],
actions: [new chrome.declarativeContent.ShowAction()],
};
// Finally, apply our new array of rules
let rules = [exampleRule];
chrome.declarativeContent.onPageChanged.addRules(rules);
});
});
I noticed that the icon on my extension grey's out on sites that don't match the specified pattern, and has color on sites that do match the url pattern (expected behavior). However, when I click on the extension on sites that match the url pattern, the extension remains disabled.
Question: Has anyone been able to get this sample code to work? How would one make a chrome extension work only when user is on specific site, and has clicked on the extension?
Thanks in advance!
You just need to add "declarativeContent" into manifest.json permissions.
"permissions": [
"declarativeContent"
],
I would like to create a chrome extension which changes my default tab in chrome browser.
Inside the page I will put my favorite websites, which I think I can handle using HTML + CSS. My difficult part is how to make it become a chrome extension because I have never done it before.
Can anyone give me some basic steps which I could start with?
You are looking for what's called Override Pages.
An extension can declare that it supplies a new newtab page. Here's a strictly minimal manifest for it:
{
"manifest_version": 2,
"name": "My awesome New Tab override",
"version": "1.0",
"chrome_url_overrides" : {
"newtab": "newtab.html"
}
}
Then you can use this manifest, together with a newtab.html and required resources, to make a simple extension.
There are many guides past that point; you can see the Learn Basics part of the official docs. Remember you can always ask a new question here if you run into specific implementation questions.
This is my first time messing around with extensions and what I am trying to do is very simple yet I can't seem to get it to work.
I simply want an alert to be called every time a page on google is loaded.
In my manifest.json I have:
{
"name": "Bypass shib",
"version": "1.0",
"content_scripts": [
{
"matches": ["http://www.google.com/*"],
"js": ["secondScript.js"]
}
],
"manifest_version": 2
}
Okay now in my secondScript.js I have:
chrome.tabs.executeScript(null, {code: "alert('test')"});
Shouldn't this execute the alert whenever a page is loaded? If not can somebody explain why it's not?
The console reveals the following message:
Uncaught Error: "executeScript" can only be used in extension processes.
See the content scripts documentation for more details.
This post suggests "Chrome extension functions cannot be used in content scripts," which could be what you're running into.
For completeness, the secondScript.js that worked for me was as follows:
console.log("test");
//chrome.tabs.executeScript(null, {code: "alert('test')"});
alert("test");
Content scripts do not have access to any of the chrome.tabs.* API methods.
To display an alert on every page, remove the chrome.tabs.executeScript method, and let your secondScript.js just contain:
alert('Test');
In a Chrome extension, there are three different kinds of scopes in which JavaScript can run. The understanding of this separation is essential for writing Chrome extensions, see this answer.
I'm new to extension development, maybe someone has a small example ready for my problem.
I plan a more complicate code (that will execute chromium API functions), but solving this task should help me get started:
I want to create an extension that triggers a popup or alert() (just anyything) based on a website javascript call.
So for example my website has a button, when clicked on the button a javascript with a few parameters is executed.
My extension picks those parameters up and executes APIs (for my example just any popup) based on the parameters.
In my basic example I'd like to trigger some sort of popup/notification with the text supplied by the website javascript.
Also only my website domain should be allowed to trigger that, anything else should be rejected.
I'd really appreciate help.
Here is my "empty" manifest
{
"name": "Special API",
"version": "1.0",
"description": "API demo extension.",
"browser_action":
{
"default_icon": "gears.ico",
"popup": "show_credits.htm"
},
"permissions": [
"http://www.mywebsite.com/"
]
}
Here the example button in my website.com/example
<html>
<body>
<button onClick="extension_do_exec('Hellow world','abcabc')">Execute extension function</button>
</body>
</html>
The approach you described is problematic, bacause javascripts of web-pages, and javascripts of extensions are isolated from each other (there is a concept of isolated world). So it is not possible to get a value "supplied by the website javascript" directly into the extension's javascript. I'd suggest another approach. You possibly could exchange with some values by assigning them as properties to DOM objects. These properties can be accessed from a content script, injected into the web-page. Of course, the content script can determine domain of the page and work as appropriate. As for popups, these are internal pages of an extension, and you should implement some kind of messaging between them and your content script.
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