Search code examples
javascriptwebviewelectron

How to open a new window with the same custom user agent in ElectronJS


Im Building a webview app in ElectronJs, Im using a Custom User Agent to make the user interact with the webApp. When the user clicks on links that has target="_blank" property, it opens a new tab and not using the custom user agent.

any ideas?


Solution

  • the target=_black will create a new browserWindow Object so a think that you could track this events with the webContents api and apply the custom userAgent to this new browserwindow objects. for example:

    you need this webContents event on your main window

    win.webContents.setWindowOpenHandler(({ url }) => {
       /* 
         Here you will allow the browserWindow creation and configure it
         look a bit of the documentation here https://www.electronjs.org/es/docs/latest/api/web-contents#contentssetwindowopenhandlerhandler
       */
    }
    

    this SetWindowOpenHandler event will allow the window creation, now with the event did-create-window you will get the new BrowserWindow object and with that reference you will be able to set the custom userAgent

    win.webContents.on('did-create-window', (childWindow) => {
      /*
         Here you can use childWindow to set the new user agent for example
         here documentation for did-create-window https://www.electronjs.org/es/docs/latest/api/web-contents#evento-did-create-window
      */
         childwindow.webContents.setUserAgent('your-custom-user-agent)
      
    });
    

    I hope that helps you, bye!