chrome.proxy API

时间:2017-11-14 23:29:03

标签: javascript google-chrome google-chrome-extension

我正在尝试使用chrome代理api,但由于某种原因我一直收到此错误。我以为我做的一切正常,但我猜不是:/

这是我的代码......

var proxy_type;
var proxy_port;
var proxy_ip;
chrome.storage.sync.get(['proxy_type', 'proxy_port', 'proxy_ip', 'proxy'], function(items) {
    console.log('Settings retrieved', Object.values(items));
    proxy_type = items.proxy_type; //this is equal to socks5
    proxy_ip = items.proxy_ip; //this is equal to 66.78.44.221
    proxy_port = parseInt(items.proxy_port); //this is equal to 58124
});
var config = {
  mode: "fixed_servers",
  rules: {
    singleProxy: {
      scheme: proxy_type,
      host: proxy_ip,
      port:proxy_port
    },
    bypassList: ["foobar.com"]
  }
};

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");  
    if (request.greeting == "connect"){
        console.log('setting proxy');
        console.log(proxy_ip); //shows 66.78.44.221 in the log...
        chrome.proxy.settings.set(
          {value: config, scope: 'regular'},
          function() {});
    }
  });

每当我运行此代码时,我都会收到错误:Error in event handler for runtime.onMessage: Error: Invalid value for argument 1. Property 'value.rules.singleProxy.host': Property is required.

如果我只是输入值而不是使用变量来设置scheme,host和port的值,那么它就可以工作。

那我为什么会收到这个错误?

1 个答案:

答案 0 :(得分:0)

错误表示配置中的主机字段可能未定义。由于chrome.storage.sync.get是异步的,我希望在定义代理参数之前构造配置对象。

您可以在回调中构造config并检查它是否在消息处理程序中定义:

var config;

chrome.storage.sync.get(['proxy_type', 'proxy_port', 'proxy_ip', 'proxy'], function(items) {
    console.log('Settings retrieved', Object.values(items));
    config = {
      mode: "fixed_servers",
      rules: {
        singleProxy: {
          scheme: items.proxy_type,
          host: items.proxy_ip,
          port: parseInt(items.proxy_port)
        },
        bypassList: ["foobar.com"]
      }
    };
});

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (!config) {
        console.log('proxy config not defined');
        return;
    }
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");  
    if (request.greeting == "connect"){
        console.log('setting proxy');
        console.log(config); //shows 66.78.44.221 in the log...
        chrome.proxy.settings.set(
          {value: config, scope: 'regular'},
          function() {});
    }
});