Merchuk Hul
Merchuk Hul

Reputation: 275

How to redirect some pages in Google chrome extension?

I am using chrome.webRequest.onBeforeRequest in my background script to listen to all request a user is making. My extension now is just a manifest and this bg script.

I then check if the url matches a regex:

chrome.webRequest.onBeforeRequest.addListener(
     checkRedirect, {urls: ["<all_urls>"]}, ["blocking"]
);

function checkRedirect(details) {   
    var location = getLocation(details.url);

    if(/some_regex/.test(details.url)) {
        var redirect_url = 'http://some_redirect.com' + location.pathname;
        chrome.tabs.update({url: redirect_url});
    }

    return {cancel: false}; 
}

function getLocation(href) {
    var l = document.createElement('a');
    l.href = href;
    return l;
};

So if a user enters a page or clicks on a link to that page, I'd like to redirect him. The code above works almost fine; the problem is when the page requests e.g. CSS then those CSS end up on the user screen.


So what I'd want is to only filter requests to pages / clicks.. how to do this?

Upvotes: 0

Views: 1418

Answers (1)

Rob W
Rob W

Reputation: 349222

Limit event notifications to the top-level frame by setting types to ['main_frame'] (use ['main_frame', 'sub_frame'] if you want to include frames as well).

Although the previous suggestion will fix your problem, I suggest to go a step further and get rid of chrome.tabs.update. Use redirectUrl to replace the previous request with a redirect to the desired URL.

If your URL-pattern matching method is very simple, expressible as a match pattern, incorporate the filter in the "urls" key of the webRequest API filter. This will reduce your extension's impact on your browser's performance.

chrome.webRequest.onBeforeRequest.addListener(function(details) {
    var location = getLocation(details.url); // getLocation defined in question
    var redirect_url = 'http://some_redirect.com' + location.pathname;
    return { redirectUrl: redirect_url };
}, {
    types: ['main_frame', 'sub_frame'],
    urls: ['*://*/*some_pattern*']
}, ['blocking']);

Note: Do not use <all_urls> if you are not prepared to handle non-http(s) requests.

Upvotes: 4

Related Questions