node.jselectronwebrequest

Electron WebRequest events produce UnhandledPromiseRejectionWarning: TypeError: Invalid url pattern


I'm trying to leverage the WebRequest onBeforeSendHeaders API. But I'm not having any luck getting it to trigger. As an experiment I tried the other APIs and I similarly see no activity.

Is there anything obviously wrong with my setup. My code looks like

const view = new BrowserView({
  webPreferences: {
    nodeIntegration: false,
    partition: LOGIN_PARTITION,
    enableRemoteModule: true
  }
})
....
view.webContents.session.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
  logger.info(`onBeforeSendHeaders called for ${details}`)
  details.requestHeaders['My-User-Agent'] = 'MyAgent'
  callback({ requestHeaders: details.requestHeaders })
})
....
view.webContents.loadURL(url.href)

I've also noticed an unexpected issue. Namely on the documentation it sets a filter like

urls: ['https://*.github.com/*', '*://electron.github.io']

but for me this produces an error, namely

UnhandledPromiseRejectionWarning: TypeError: Invalid url pattern *://electron.github.io: Empty path.

I'm using an old version of Electron (10.1.5) and NodeJS (v10.24.1). I'm wondering if they are causing issues.

Update

Created a repo to demonstrate this issue at https://github.com/sregger/electron-webrequest

Here I'm using Electron 16 and NodeJS 16


Solution

  • Figured out the issue, which I had not included in the sample above. The problem was

    const filter = null
    

    which I put in place because using undefined throws

    (node:831) UnhandledPromiseRejectionWarning: TypeError: Must pass null or a Function
    

    Based on the following documentation

    The filter object has a urls property which is an Array of URL patterns that will be used to filter out the requests that do not match the URL patterns. If the filter is omitted then all requests will be matched.

    I assumed the entire object should be undefined, then null due to the above. Instead it should be

    const filter = {
          urls: []
        }
    

    When null is used no url matches. When an empty array is used all urls match.