How to set electron UserAgent
Asked Answered
S

4

35

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.

Softspoken answered 27/2, 2016 at 16:57 Comment(0)
J
30

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 });
});
Jitter answered 27/2, 2016 at 17:28 Comment(3)
Make sure you have version >=0.36.1 for this. Otherwise it won't work. Just spent way too long figuring that out.Guidry
@Guidry No, you just need to provide a filter (or undefined) before callbacks parameters ;)Quadrangular
Also be aware that you can't access session until the app ready event has fired!Cartier
D
30

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
   });
}
Demarcate answered 31/8, 2016 at 11:19 Comment(1)
For future reference: If you want to extend the user agent instead of overwriting it, you can get the original user agent via win.webContents.getUserAgent().Mysia
A
24

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.


Electron 8.2.5 Update

In newer versions, setUserAgent method will be deprecated. Instead, use this;

mainWindow.webContents.userAgent //to get
mainWindow.webContents.userAgent = "Something" //to set
Asocial answered 18/11, 2018 at 22:49 Comment(2)
While this works for the the initial window, links clicked within that window seem to lose the user agent. Passing { userAgent: "my custom ua" } as an option to the original loadURL() call seems to get around this.Subirrigate
@Subirrigate It's been a while since I was mingling with electron. I'm assuming that you are using target=_blank in that case you are creating a new window, so that wouldn't use the same user agent. In that case you should check out setWindowOpenHandler method. You can modify default behavior.Asocial
P
3

Just use this if you're using a <webview> tag, this works better for me

<webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>
Ponzo answered 2/8, 2019 at 20:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.