Reputation: 2325
I want to build a chrome extension which essentially checks if the current domain is in a list, if so redirect the user to a different url, lets him click a link and than goes to the initially wanted url.
I don't have much experience with Javascript or chrome extensions, but this seems easy enough for a starters project.
What I want to to is to have a file of this structure
urlregex1#redirecttourl1
urlregex2#redirecttourl2
.
.
.
and have a chrome content_script parse every url and check if one of the regular expressions matches.
If so the script has to somehow save the original url and than redirect the user.
Can anyone put me in the right direction on how to implement this? I'm totally lost between javascript functions, chrome extension api,....
Upvotes: 0
Views: 2396
Reputation: 2066
You will have to set up the functionality in your background page so that it runs on all tabs.
// add listener for all tabs
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
var safesite = false;
if (changeInfo === "loading") {
// logic for checking white list, using tab.url
if (!safesite) {
chrome.tabs.update(tabId, { url: 'www.google.com' });
}
}
});
Essentially, you're adding an event listener to all tabs. When its loading, you check to see if its on the white list. If its a black-listed site, redirect them to whatever url you like. You can also included a .html file in the extension directory to re-direct them to as well. This fires on all tabs, including the Web Inspector so you may want to put in some logic to only check http(s) requests.
Also, this approach COULD show the black-listed page briefly and THEN re-direct you to the blocked_url.html page. The experimental API, webRequest, should provide the ability to filter the request BEFORE loading the page but you won't be able to upload that to the Chrome Web Store until its becomes part of the official Chrome API. If its for personal use then feel free to use it.
One last tip for development: you can only debug the background.html through the Extensions settings page (chrome://settings/extensionSettings). Open the drill down for your extension and you'll see 'Inspect active views:' where you can you click a link to whatever extension-specific pages you have currently running. Doing so will bring up the Web Inspector for that page.
After much head scratching, I came across that accidentally and it has been life-saver ever since.
Upvotes: 4