Accessing the DOM of the <webview> element in Electron typically requires a preload script to ensure security and isolation. Below are the specific steps and examples:
Step 1: Create the preload script
In the preload script, use the contentWindow property of the webview to access its DOM. For example, create a file named preload.js with the following content:
javascript// preload.js const { contextBridge } = require('electron'); contextBridge.exposeInMainWorld('webviewAPI', { getTitle: function(callback) { document.addEventListener('DOMContentLoaded', () => { const title = document.title; callback(title); }); } });
Here, we define a getTitle method that retrieves document.title after the DOMContentLoaded event and returns it via a callback.
Step 2: Use the preload script in the <webview> tag
In the HTML file, correctly set the preload attribute of the <webview> element to point to your preload.js file:
html<webview id="foo" src="https://example.com" preload="./preload.js"></webview>
Step 3: Access DOM information from the main process
From the main process, use the webview API to call methods defined in the preload script. For example, to retrieve the page title:
javascriptlet webview = document.getElementById('foo'); webview.addEventListener('dom-ready', function() { window.webviewAPI.getTitle((title) => { console.log('Page title is:', title); }); });
Summary
This approach safely allows indirect access to the <webview> DOM from Electron's main process without violating the content security policy. Additionally, it protects user privacy and application security by limiting direct DOM manipulation.
Using a preload script provides explicit control over which features or data can be exposed from the renderer process to the main process, thereby enhancing overall application security.