javascriptgoogle-chrome-extensionpac

How to check response of Pac script


I need to get the response of the pacScript in my chrome extension.A pacScript will return DIRECT string in case we don't need to proxy and i want to detect that.

var config = {
        mode: "pac_script",
        pacScript: {
          url: "https://www.example.com/proxy.pac"
        }
      };

chrome.proxy.settings.set({value: config, scope: 'regular'},function() {
    //how can i get the pac response string here 
});

Edit : I tried using JQuery.getScript to load the FindProxyForURL from remote pac file but now the pac specific function like isPlainHostName are now undefined.

I could get the implementations from mozilla but there must be a better way since those are browser functions that should have already been available.


Solution

  • What you're trying to do is simply not possible. This is because a pac file is evaluated for each url you request. So, the 'pac response string' is not a constant that can be returned upon setting the proxy settings.

    If you're trying to debug your pac file, you can alert('settings') inside the FindProxyForURL just before returning the settings. The alert creates a log entry which can be accessed via chrome://net-internals/#events functionality.

    If you only want to test if the user is using direct connection or proxy, you can compare the external ip address before and after setting proxy settings. Checkout ipify.org or you can even use a script on your own web server.

    Here's some sample code for this:

    let originalIp = "";
    
    async function getCurrentIp() {
        var res = await fetch('http://api.ipify.org/');
        return await res.text();
    }
    
    // Get ip before setting proxy
    getCurrentIp().then(ip => {
        originalIp = ip;
    });
    
    var config = {
        mode: "pac_script",
        pacScript: {
            url: "https://www.example.com/proxy.pac"
        }
    };
    
    chrome.proxy.settings.set({
        value: config,
        scope: 'regular'
    }, function() {
        // Get ip after setting proxy and compare it with original ip
        getCurrentIp().then(ip => {
            if (ip == originalIp)
                console.log('DIRECT');
            else
                console.log('PROXY: ' + ip)
        })
    });