簡體   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