繁体   English   中英

chrome.proxy API出现问题

[英]Problems with chrome.proxy API

我正在尝试使用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的值,则它可以工作。

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

该错误表明配置中的host字段可能未定义。 由于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() {});
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM