javascript - Modifying User-Agent in Electron blocks Requests to a specific Domain - Stack Overflow

admin2025-04-17  4

I am building a custom Electron-based browser and modifying the User-Agent dynamically for certain domains. However, after removing Electron/\* from the User-Agent for a specific demo gaming website, the site fails to load and throws JavaScript errors.

I intercept all outgoing requests and modify the User-Agent in my Electron main.js like this:

session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    const originalUserAgent = details.requestHeaders['User-Agent'];
    const newUserAgent = getUserAgentForURL(originalUserAgent, details.url);

    console.log('========================');
    console.log('Intercepted Request:');
    console.log('URL:', details.url);
    console.log('Original User-Agent:', originalUserAgent);
    console.log('Modified User-Agent:', newUserAgent);
    console.log('========================');

    details.requestHeaders['User-Agent'] = newUserAgent;
    callback({ cancel: false, requestHeaders: details.requestHeaders });
});

And my user-agent.js modifies the User-Agent like this:

const { app } = require('electron');

const REMOVE_ELECTRON_COMPONENTS = [
  / Electron\/([^\s]+)/g,  // Removes Electron
  ` ${app.name}/${app.getVersion()}`, // Removes app-specific info
];

function getUserAgentForURL(userAgent, url) {
  if (typeof userAgent !== 'string') {
    console.error(`Error: Expected userAgent to be a string, but got ${typeof userAgent}`);
    return userAgent || 'Mozilla/5.0';
  }

  let componentsToRemove = [...REMOVE_ELECTRON_COMPONENTS];

  // Remove Electron-specific components but keep Chrome
  componentsToRemove.forEach((x) => {
    if (userAgent) {
      userAgent = userAgent.replace(x, '');
    }
  });

  return userAgent;
}

module.exports = { getUserAgentForURL };

Debugging Output:
When I try to access a demo game website, I get the following logs:

========================
Intercepted Request:
URL: https://[removed-domain]/game-assets/other_resources.json
Original User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) my-electron-app/1.0.0 Chrome/132.0.6834.159 Electron/34.0.2 Safari/537.36
Modified User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.6834.159 Safari/537.36
========================

However, the website does not load and throws JavaScript errors in the console:

[96308:0201/114327.613:INFO:CONSOLE(5657)] "Uncaught TypeError: Cannot read properties of undefined (reading 'split')", 
source: https://[removed-domain]/build.js (5657)

[96308:0201/114327.616:INFO:CONSOLE(18588)] "Uncaught TypeError: Cannot read properties of null (reading 'length')", 
source: https://[removed-domain]/logo_info.js (18588)

When I do not modify the User-Agent, the website works perfectly and sends the following successful request:

========================
Intercepted Request:
URL: https://[removed-domain]/gs2c/ge/v4/game
Method: POST
Headers: {
  "host": "[removed-domain]",
  "connection": "keep-alive",
  "content-length": "145",
  "accept": "*/*",
  "accept-encoding": "gzip, deflate, br, zstd",
  "accept-language": "en-US",
  "content-type": "application/x-www-form-urlencoded",
  "origin": "https://[removed-domain]",
  "referer": "https://[removed-domain]/gs2c/html5Game.do?extGame=1&symbol..",
  "sec-fetch-dest": "empty",
  "sec-fetch-mode": "cors",
  "sec-fetch-site": "same-origin",
  "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) my-electron-app/1.0.0 Chrome/132.0.6834.159 Electron/34.0.2 Safari/537.36",
  "sec-ch-ua": "\"Not A(Brand\";v=\"8\", \"Chromium\";v=\"132\"",
  "sec-ch-ua-mobile": "?0",
  "sec-ch-ua-platform": "\"Windows\""
}
========================

How can I successfully modify the User-Agent?

UPDATE

I tested modifying the User-Agent using the "User-Agent Switcher for Chrome" extension. However, the game still did not load, indicating that Chrome ignored the extension's changes.

Upon further investigation, I discovered the "Use browser default User-Agent" setting in DevTools → Network Conditions:

Opened DevTools (F12) → Network Tab. Clicked the Wi-Fi icon (bottom left). Found "Use browser default User-Agent" enabled by default. This setting causes inconsistencies, as requests use the modified User-Agent, but the browser continues using its default value internally, likely confusing the JavaScript code.

To resolve this:

Unchecked "Use browser default User-Agent". Manually entered the modified User-Agent. Reloaded the game → It worked correctly. Question: Since this setting is controlled by Chromium, how can we disable "Use browser default User-Agent" automatically in Electron?

Is there a command-line flag or API in Electron/Chromium to override this setting?

I am building a custom Electron-based browser and modifying the User-Agent dynamically for certain domains. However, after removing Electron/\* from the User-Agent for a specific demo gaming website, the site fails to load and throws JavaScript errors.

I intercept all outgoing requests and modify the User-Agent in my Electron main.js like this:

session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    const originalUserAgent = details.requestHeaders['User-Agent'];
    const newUserAgent = getUserAgentForURL(originalUserAgent, details.url);

    console.log('========================');
    console.log('Intercepted Request:');
    console.log('URL:', details.url);
    console.log('Original User-Agent:', originalUserAgent);
    console.log('Modified User-Agent:', newUserAgent);
    console.log('========================');

    details.requestHeaders['User-Agent'] = newUserAgent;
    callback({ cancel: false, requestHeaders: details.requestHeaders });
});

And my user-agent.js modifies the User-Agent like this:

const { app } = require('electron');

const REMOVE_ELECTRON_COMPONENTS = [
  / Electron\/([^\s]+)/g,  // Removes Electron
  ` ${app.name}/${app.getVersion()}`, // Removes app-specific info
];

function getUserAgentForURL(userAgent, url) {
  if (typeof userAgent !== 'string') {
    console.error(`Error: Expected userAgent to be a string, but got ${typeof userAgent}`);
    return userAgent || 'Mozilla/5.0';
  }

  let componentsToRemove = [...REMOVE_ELECTRON_COMPONENTS];

  // Remove Electron-specific components but keep Chrome
  componentsToRemove.forEach((x) => {
    if (userAgent) {
      userAgent = userAgent.replace(x, '');
    }
  });

  return userAgent;
}

module.exports = { getUserAgentForURL };

Debugging Output:
When I try to access a demo game website, I get the following logs:

========================
Intercepted Request:
URL: https://[removed-domain]/game-assets/other_resources.json
Original User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) my-electron-app/1.0.0 Chrome/132.0.6834.159 Electron/34.0.2 Safari/537.36
Modified User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.6834.159 Safari/537.36
========================

However, the website does not load and throws JavaScript errors in the console:

[96308:0201/114327.613:INFO:CONSOLE(5657)] "Uncaught TypeError: Cannot read properties of undefined (reading 'split')", 
source: https://[removed-domain]/build.js (5657)

[96308:0201/114327.616:INFO:CONSOLE(18588)] "Uncaught TypeError: Cannot read properties of null (reading 'length')", 
source: https://[removed-domain]/logo_info.js (18588)

When I do not modify the User-Agent, the website works perfectly and sends the following successful request:

========================
Intercepted Request:
URL: https://[removed-domain]/gs2c/ge/v4/game
Method: POST
Headers: {
  "host": "[removed-domain]",
  "connection": "keep-alive",
  "content-length": "145",
  "accept": "*/*",
  "accept-encoding": "gzip, deflate, br, zstd",
  "accept-language": "en-US",
  "content-type": "application/x-www-form-urlencoded",
  "origin": "https://[removed-domain]",
  "referer": "https://[removed-domain]/gs2c/html5Game.do?extGame=1&symbol..",
  "sec-fetch-dest": "empty",
  "sec-fetch-mode": "cors",
  "sec-fetch-site": "same-origin",
  "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) my-electron-app/1.0.0 Chrome/132.0.6834.159 Electron/34.0.2 Safari/537.36",
  "sec-ch-ua": "\"Not A(Brand\";v=\"8\", \"Chromium\";v=\"132\"",
  "sec-ch-ua-mobile": "?0",
  "sec-ch-ua-platform": "\"Windows\""
}
========================

How can I successfully modify the User-Agent?

UPDATE

I tested modifying the User-Agent using the "User-Agent Switcher for Chrome" extension. However, the game still did not load, indicating that Chrome ignored the extension's changes.

Upon further investigation, I discovered the "Use browser default User-Agent" setting in DevTools → Network Conditions:

Opened DevTools (F12) → Network Tab. Clicked the Wi-Fi icon (bottom left). Found "Use browser default User-Agent" enabled by default. This setting causes inconsistencies, as requests use the modified User-Agent, but the browser continues using its default value internally, likely confusing the JavaScript code.

To resolve this:

Unchecked "Use browser default User-Agent". Manually entered the modified User-Agent. Reloaded the game → It worked correctly. Question: Since this setting is controlled by Chromium, how can we disable "Use browser default User-Agent" automatically in Electron?

Is there a command-line flag or API in Electron/Chromium to override this setting?

Share Improve this question edited Feb 2 at 7:36 August asked Feb 1 at 15:22 AugustAugust 411 silver badge4 bronze badges 2
  • Do the lines in the error stack trace give any meaningful information? Can you otherwise include them in your question? even if it's minified it could help find the issue. You could also temporarily disable minification to make it easier, so build.js line 5657 and logo_info.js 18588 – shotor Commented Feb 1 at 23:58
  • build.js is 100k line code, bundled. The error is due to some objects not being properly initialized. Luckily I found a way out. – August Commented Feb 2 at 7:43
Add a comment  | 

1 Answer 1

Reset to default 0

I found that Chromium was forcing the default User-Agent internally, causing inconsistencies between requests and the browser’s JavaScript runtime. The fix was setting app.userAgentFallback, which I came across in Electron’s documentation. It was a hit-and-try approach, but it worked.

app.whenReady().then(() => {
  app.userAgentFallback = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36";
});

app.userAgentFallback A string which is the user agent string Electron will use as a global fallback.

This is the user agent that will be used when no user agent is set at the webContents or session level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used.

Source : Electron Documentation

转载请注明原文地址:http://anycun.com/QandA/1744825311a88138.html