P
P
patsanchique2021-09-08 17:59:21
Google Chrome
patsanchique, 2021-09-08 17:59:21

How to implement https proxy with authorization in your chrome extension?

There was a need for an extension - an https proxy switcher with authorization by a specific trigger, the question is: how to fasten these same proxies? I would be grateful for any information on this matter.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nadim Zakirov, 2021-09-09
@patsanchique

In the background process of the background.js extension, write:

Expand
// Записываем параметры прокси в глобальную переменную:

window.proxy_auth = {
  'address': 'Адрес_прокси:Порт_прокси',
  'proxy_user': 'Логин от прокси',
  'proxy_password': 'Пароль от прокси'
};

// Устсновка прокси через назначение PAC-скрипта:

chrome.proxy.settings.set(
  {
    value: {
      mode: 'pac_script',
      pacScript: {
        data: 'function FindProxyForURL(url, host) { return "PROXY '+proxy_auth.addres+'"; }'
      }
    },
    scope: 'regular'
  },
  function() {
    console.log('Прокси '+proxy_auth.addres+' установлен');
  }
);

// Автоматическая авторизация для установленного прокси:

chrome.webRequest.onAuthRequired.addListener(
  function(info, callback) {
    if (info.isProxy && typeof window.proxy_auth !== 'undefined') {
      callback({
        authCredentials: {
          username: window.proxy_auth.proxy_user,
          password: window.proxy_auth.proxy_password
        }
      });
    }
    else {
      callback();
    }
  },
  { urls: [ '<all_urls>' ] },
  [ 'asyncBlocking' ]
);

You must have permissions in your extension manifest:
Expand
{
  
  "name" : "Имя расширения",
  
  "manifest_version" : 2,
    
  "permissions" : [ "proxy", "webRequest", "webRequestBlocking", "<all_urls>" ],
  
  "background" : { "persistent": true, "scripts": [ "background.js" ] }

}

PS You can reset a previously set proxy by installing an empty PAC script, something like this:
Expand
chrome.proxy.settings.set(
  {
    value: {
      mode: 'pac_script',
      pacScript: {
        data: 'function FindProxyForURL(url, host) { return "DIRECT"; }'
      }
    },
    scope: 'regular'
  },
  function() {
    console.log('Прокси сброшены');
  }
);

R
Rsa97, 2021-09-08
@Rsa97

https://developer.chrome.com/docs/extensions/refer...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question