How to set electron UserAgent

2019-02-17 03:47发布

I need to set the UserAgent in electron to include the touch flag since I am writing the application for touch screens and it doesn't seem to auto detect that it is running on a touch screen.

Any help would be nice, I already tried setting it in the BrowserWindow.loadURL options param.

3条回答
霸刀☆藐视天下
2楼-- · 2019-02-17 04:11

You can set the User-Agent header in the main process using onBeforeSendHeaders:

import { session } from 'electron';

session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
  details.requestHeaders['User-Agent'] = 'SuperDuperAgent';
  callback({ cancel: false, requestHeaders: details.requestHeaders });
});
查看更多
聊天终结者
3楼-- · 2019-02-17 04:12

Before loading file, you can call BrowserWindowInstance.webContents.setUserAgent()

mainWindow.webContents.setUserAgent(mainWindow.webContents.getUserAgent() + " Custom Value");
mainWindow.loadFile('renderer/index.html');

Works with electron 3.0.4 Previous solutions didn't work for me.

查看更多
我只想做你的唯一
4楼-- · 2019-02-17 04:32

Just use an option object when loading the URL.

function createWindow () {
   win = new BrowserWindow({width: 800, height: 600});
   win.loadURL('http://www.whoishostingthis.com/tools/user-agent/',
     {userAgent: 'Chrome'});

   win.on('closed', () => {
     win = null
   });
}
查看更多
登录 后发表回答