我正在使用 Electron 创建简单的 Web 浏览器。我的用例是我需要通过不同/各自的代理 IP 路由每个 URL。如果用户键入google.com它必须通过路由123.123.122.1:8081
,如果他键入gmail.com
它必须通过111.111.111.123:8080
[代理/端口]路由。我看到了这一点,http://stackoverflow.com/questions/37393248/how-connect-to-proxy-in-electron-webview?rq=1
但它不会动态更改代理。是否可以在电子中做到这一点。
有两种方法可以解决此问题。\n您可以使用 proxy.pac 方法或会话/代理规则来更改代理
\n\n持久会话方法:
\n\nvar proxyIp =\'12.12.133.12\xe2\x80\x99\nvar port =\xe2\x80\x988080\xe2\x80\x99\n\n<webview id="wv1" src="https://github.com" partition="persist:webviewsession"></webview>\n\nif(proxyIp.trim() ==\'noproxy\'){\n var my_proxy = \'direct://\';\n session.fromPartition(\'persist:webviewsession\').setProxy({proxyRules:my_proxy}, function (){\n console.log(\'using the proxy \' + proxyIp);\n });\n\n}else{\n var my_proxy = "http://"+proxyIp+":"+port;\n session.fromPartition(\'persist:webviewsession\').setProxy({proxyRules:my_proxy}, function (){\n console.log(\'using the proxy \' + proxyIp);\n });\n}\n
Run Code Online (Sandbox Code Playgroud)\n\nproxy.pac方法
\n\n代理.js
\n\nconst {app, BrowserWindow} = require(\'electron\');\nconst {session} = require(\'electron\')\nlet mainWindow;\napp.on(\'window-all-closed\', function() {\n app.quit();\n});\n\n app.on(\'ready\', function() {\n mainWindow = new BrowserWindow({width: 1024, height: 768 });\n session.defaultSession.allowNTLMCredentialsForDomains(\'*\')//to access internal sites\n\nvar myVar = setInterval(myTimer, 3000);\nfunction myTimer() {\n mainWindow.webContents.session.setProxy({pacScript:\'file://\' + __dirname + \'/proxy.pac\'}, function () {return true;});\n}\n\nmainWindow.webContents.session.setProxy({pacScript:\'file://\' + __dirname + \'/proxy.pac\'}, function () {mainWindow.loadURL(\'file://\' + __dirname + \'/browser.html\');});\n mainWindow.openDevTools();\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n代理.pac
\n\nfunction FindProxyForURL(url, host) {\n\n if (shExpMatch(url, "*google*"))\n return "PROXY 164.83.99.74:80";\n\n if (shExpMatch(url, "*amazon*"))\n return "PROXY 194.73.29.74:8080";\n\n return "DIRECT";\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n\nProxy.pac 文件可以位于某些 S3 位置或其他远程服务器或本地,因此即使您更改远程 proxy.pac 文件也会反映在电子工具中。 proxy.pac 方法的问题是当您更改代理 IP 时proxy.pac 你需要在电子中重新加载 proxy.pac 文件,这就是为什么我在上面的代码中每 3 秒重新加载一次。
\n\n两者都可以正常工作,我自己测试了两者。\n您可以根据您的用例使用任何一个。
\n\n详细讨论可以在这里找到\n https://discuss.atom.io/t/how-to-set-proxy-for-each-webview-tag-in-electronjs/37307/2
\n\n电子文档:https://github.com/electron/ electron /blob/master/docs/api/session.md#sessetproxyconfig-callback
\n\n来自电子维护者的建议:\n https://github.com/electron/electron/issues/8247#issuecomment-268435712
\n 归档时间: |
|
查看次数: |
3156 次 |
最近记录: |