Reputation: 1102
I am creating simple web browser using Electron. My use case is I need to route each URL via different/respective proxy-IPs. If the user type google.com it has to route via 123.123.122.1:8081
and if he type gmail.com
it has to route via 111.111.111.123:8080
[Proxy/Port].I saw this http://stackoverflow.com/questions/37393248/how-connect-to-proxy-in-electron-webview?rq=1
but it will not change proxy dynamically. Is it possible to do it in electron.
Upvotes: 5
Views: 5211
Reputation: 1102
There are two ways to solve this problem. Either you can use proxy.pac method or session/proxy rules to change the proxy
persist session method :
var proxyIp ='12.12.133.12’
var port =‘8080’
<webview id="wv1" src="https://github.com" partition="persist:webviewsession"></webview>
if(proxyIp.trim() =='noproxy'){
var my_proxy = 'direct://';
session.fromPartition('persist:webviewsession').setProxy({proxyRules:my_proxy}, function (){
console.log('using the proxy ' + proxyIp);
});
}else{
var my_proxy = "http://"+proxyIp+":"+port;
session.fromPartition('persist:webviewsession').setProxy({proxyRules:my_proxy}, function (){
console.log('using the proxy ' + proxyIp);
});
}
proxy.pac method
proxy.js
const {app, BrowserWindow} = require('electron');
const {session} = require('electron')
let mainWindow;
app.on('window-all-closed', function() {
app.quit();
});
app.on('ready', function() {
mainWindow = new BrowserWindow({width: 1024, height: 768 });
session.defaultSession.allowNTLMCredentialsForDomains('*')//to access internal sites
var myVar = setInterval(myTimer, 3000);
function myTimer() {
mainWindow.webContents.session.setProxy({pacScript:'file://' + __dirname + '/proxy.pac'}, function () {return true;});
}
mainWindow.webContents.session.setProxy({pacScript:'file://' + __dirname + '/proxy.pac'}, function () {mainWindow.loadURL('file://' + __dirname + '/browser.html');});
mainWindow.openDevTools();
});
proxy.pac
function FindProxyForURL(url, host) {
if (shExpMatch(url, "*google*"))
return "PROXY 164.83.99.74:80";
if (shExpMatch(url, "*amazon*"))
return "PROXY 194.73.29.74:8080";
return "DIRECT";
}
Proxy.pac file can be in some S3 location or in some other remote server or local so even if you change remote proxy.pac file that will reflect in electron tool.Issue with proxy.pac method is when ever you are changing proxy IP in proxy.pac u need to reload proxy.pac file in electron that's why i am reloading every 3 sec in above code.
Both will work fine and I tested both myself. You can use any based on your usecase.
Detailed discussion can be found here https://discuss.atom.io/t/how-to-set-proxy-for-each-webview-tag-in-electronjs/37307/2
Electron Document : https://github.com/electron/electron/blob/master/docs/api/session.md#sessetproxyconfig-callback
Suggestion from electron maintainer : https://github.com/electron/electron/issues/8247#issuecomment-268435712
Upvotes: 3