Analyze request and decide action, Chrome extension

Asked

Viewed 232 times

0

How to manipulate a url request before opening the page on google Chrome? Searching I found how to block the request of a specific url, but I’m a little confused with how to manipulate the url and redirect.

Example blocking link protector url ouo.io:

chrome.webRequest.onBeforeRequest.addListener(
  function(detalhes) {
    return {cancel: detalhes.url.indexOf("://ouo.io/") != -1};
  },
  { urls: ["<all_urls>"] },
  ["blocking"]
);

However I would like to manipulate the URL in some cases, example take the URL of a parameter and redirect: ?s=

http://ouo.io/s/1XTIn2cB?s=https://google.com

1 answer

1


If detalhes.url returns a string exactly like:

http://ouo.io/s/1XTIn2cB?s=https://google.com

You can use the API URL that is native, to manipulate and extract specific data, as I said in this answer What’s $(this.hash) in jQuery for?

In your case we’ll use the URL.searchParams to take the value of s=, example of a string:

var urlDaExtensao = 'http://ouo.io/s/1XTIn2cB?s=https://google.com';
var params = new URL(urlDaExtensao).searchParams;
var qValue = params.get('s');

console.log(qValue);

See that the console.log will send the result to the console, so you could use this to redirect the current tab with the property redirectUrl, being like this:

chrome.webRequest.onBeforeRequest.addListener(function (detalhes) {
    if (detalhes.url.indexOf("://ouo.io/") != -1) {

        var urlDaExtensao = detalhes.url;
        var params = new URL(urlDaExtensao).searchParams;
        var qValue = params.get('s');

        //Se tiver um valor redireciona
        if (qValue) {
            return { "redirectUrl": qValue };
        } else {
            //Se não tiver o valor do direcionamento cancela a requisição
            return { "cancel": true };
        }
    } else {
        //Se for outra URL não cancela
        return { "cancel": false };
    }
}, {
    urls: [ "<all_urls>" ]
}, [ "blocking" ]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.