How to Set Electron Useragent

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.

4 Answers

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

Just use an option object when loading the URL.

function createWindow () {
   win = new BrowserWindow({width: 800, height: 600});
   win.loadURL('
     {userAgent: 'Chrome'});

   win.on('closed', () => {
     win = null
   });
}
1

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
2

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

<webview src="" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>
Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article