Retrieve the user-inputted data from an Electron BrowserView's input field

Consider this scenario where a BrowserWindow is set up with specific security settings, including enabling the webviewTag: true for project requirements.

let webPrefs = {
    plugins: false,
    nodeIntegration: false,
    nodeIntegrationInWorker: false,
    webviewTag: true,
    sandbox: true,
    enableRemoteModule: false,
    contextIsolation: true,
    disableBlinkFeatures: "Auxclick",
    webSecurity: true
};

let winOpts = {
    ...
    show: true,
    webPreferences: webPrefs
};

...

win = new BrowserWindow(winOpts);
const view = new BrowserView(winOpts);
win.setBrowserView(view);

...

view.webContents.loadURL("https://example.com").then(result => {
....
});

Suppose the website example.com has a <form> with various <input> fields for user input.

Users will interact by typing text into these <input> fields.

The goal is to extract the 'manually filled' text from these <input> fields without the ability to modify the webpage.

While webContents.executeJavaScript() can initiate actions, extracting the actual input values to the main process remains unclear.

(Filling out forms from the main process can be achieved using the mentioned function.)

How can we accomplish this task?

Answer №1

When importing ipcMain from electron in your main file, make sure to do it like this:

const { ipcMain, app, BrowserWindow,BrowserView } = require("electron");

In the webPrefs, include a preload file. For example:

let webPrefs = {
    plugins: false,
    nodeIntegration: false,
    nodeIntegrationInWorker: false,
    webviewTag: true,
    sandbox: true,
    enableRemoteModule: false,
    contextIsolation: true,
    disableBlinkFeatures: "Auxclick",
    webSecurity: true,
    preload:"./preload.js"
};

Create a new preload file named "preload.js". You can name it as you wish, just ensure to set the correct filename in the preload above.

This file acts as a bridge between your webview and main process. It runs before the renderer process is loaded and has access to both renderer globals (e.g. window and document) and a Node.js environment.

Add the following code to your preload.js file:

const { ipcRenderer } = require("electron");

window.addEventListener("input", (e) => {
  //dom_element_id = the id of input element you want
  if (e.target.id === "dom_element_id")
    ipcRenderer.invoke("INPUT_OCCURED", e.target.value);
});

Now, in your main file, for instance, you can add:

  win.loadURL("https://www.example.com");

  ipcMain.handle("INPUT_OCCURRED", (event, data) => {
    console.log(data);
  });

That's all the code you need. Here's a further explanation:
The preload file loads before the webview content and can execute any tasks. It also has access to Node features. We utilize IPC to communicate between the preload script and the main process. By adding a global listener in the preload file that listens to all input events, we check if the ID matches the specified element. If so, the value of the DOM element is sent to the main process. The main process handles the event data received on the INPUT_OCCURRED channel.

The reason for using a global listener instead of attaching one directly to the element is for simplicity in this example scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which element from the context menu has been selected?

We specialize in creating browser extensions for Chrome, Firefox, and Safari. Our latest project involves implementing context menus within the extensions that will appear when users right-click on any editable form element. I attempted to incorporate an e ...

Struggling to accurately convert the string into a date object

I have an array of objects structured like this: const days = [ { _id: 12312323, date : '30/12/2021', dateStatus : 'presence' }, ... ] I am looking to convert the date property from a string to a Date object using the follo ...

What could be the reason for the scope being empty in my AngularJS application?

I'm new to Angular and I'm currently customizing the tutorial for my app. However, I'm facing an issue with adding routes to my app. The templates are not being read correctly and the controller seems to have some issues as well. In order to ...

What could be causing the error "Cannot read the state property of undefined" to occur in my code?

I am facing an issue with my constructor that suddenly stopped working and I can't seem to figure out why. Upon analyzing the data, it appears that at line 24, everything is being read correctly including props. However, just one line later when tryi ...

Determine the number of items in an array with JavaScript in Node

Looking to create a new variable that counts the names in an array and assigns them accordingly? I'm currently stuck on this task. The array contains names: names = [Jan, Jan, Jana] Counting the names is simple, but I'm facing difficulty in org ...

Having trouble retrieving values from my EXPRESS / NodeJs response error message: [String: 'Error: Request resulted in an error code: 404'

I have been attempting to retrieve values from my express response error. When I use console.log on the error like so... app.use(function(err, req, res, next){ console.log(err) }); The content displayed in the console is as follows: [String: 'E ...

Issue in d3.js: bisector consistently returning zero

http://jsfiddle.net/rdpt5e30/1/ const data = [ {'year': 2005, 'value': 771900}, {'year': 2006, 'value': 771500}, {'year': 2007, 'value': 770500}, {'year': 2008, 'value&apos ...

What could be the reason for NPM failing to work following an update?

Just two days ago, I updated NPM and now it's suddenly not working on my Windows 10 20H2 platform. Every action I take results in the same error message: C:\Users\ethan>npm internal/modules/cjs/loader.js:883 throw err; ^ Error: Canno ...

Exploring the concept of JavaScript nested promise scopes within the context of AngularJS

I've been struggling with JavaScript promises for the past few hours, trying to fix a problem that I just can't seem to solve. My knowledge of promises is limited, so I'm open to the possibility that my approach might be incorrect. Currentl ...

Regex pattern to replace the zero preceding two times within a string based on distinct criteria

I need to transform the string XY4PQ43 using regex in JavaScript. The output should be XY04PQ0043. Specifically, I want to add a zero prefix to the first number if it is a single digit to ensure it has 2 digits, and for the second number in the string, I w ...

Exploring the features of React.js version 16

I'm confused about what {...props} does. I know it makes passing props easier, but what happens if there are no props to begin with? Take this example: const input = (props) => { let inputElement = null; switch(props.inputtype) { ...

The texture failed to load onto the 3D object during the mapping process

Issues with loading texture into the 3D ring model, although it works fine for other objects. No compile errors detected. Proper lighting conditions are set up but the color of the 3D model appears grey/black. The texture loads correctly for other object ...

Occasionally, Node.js is throwing an UnhandledPromiseRejection error, and it seems like my catch block is

Here is a snippet of my code: router.get('/myapi/someotherapi/:id', (request, response) => { console.log('api: GET /admin/myapi/someotherapi/:id'); console.log('Reject star redeem requests by id'); auth.verifyTo ...

The node is currently operating on a non-existent version

While attempting to set up Strapi in my Angular project, an error arises: The Node.js version running is 14.20.0 Strapi mandates using a Node.js version between >=16.0.0 and <=20.x.x Kindly ensure that the correct Node.js version is being used The i ...

Personalized Svelte interface Slider tag

I am trying to customize the label of a smui/slider in a tick marks and discrete slider. While I found instructions on how to do this using material web components at https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc- ...

I have no interest in using vanilla JavaScript to search for data in the database

I have a class assignment that requires the use of XMLHTTPREQUEST and JSON without using Jquery. The task involves searching for specific data through custom inputs. However, when I perform the search, I encounter this error which I'm unsure how to r ...

A guide to monitoring and managing errors in the react-admin dataProvider

Rollbar has been successfully integrated into my react-admin app to track uncaught errors. However, I've noticed that errors thrown by the dataProvider are not being sent to Rollbar. It seems like errors from the dataProvider are internally handled w ...

Methods for transferring data from an AJAX function

I have a database containing various links that I would like to retrieve and store within an array. I attempted to achieve this using the following code: var amz = new Array(); function CreateAmazonArray() { $.ajax({ url: "php/amazon_affilia ...

Interact with AJAX form to dynamically display result data in the intended DIV

Seeking assistance from experienced JS users! Although most features are functional, including results being returned and forms submitting to MC database, I am encountering an issue where the result html is appearing in the incorrect DIV. Instead of displ ...

Javascript Google Maps API is not working properly when trying to load the Gmap via a Json

Trying to display a map using Gmaps and Jquery Ajax through JSON, but encountering difficulty in getting the map to appear on the page. The correct coordinates are being retrieved as confirmed by testing in the console. Puzzled by why it's not showin ...