Add WebContents insertCSS functionality

This commit is contained in:
Noah Fichter
2021-04-26 12:41:14 -04:00
parent 30941df39c
commit a4d261a4e7
4 changed files with 56 additions and 2 deletions

View File

@@ -258,6 +258,18 @@ namespace ElectronNET.API
return taskCompletionSource.Task;
}
/// <summary>
/// Inserts CSS into the web page.
/// See: https://www.electronjs.org/docs/api/web-contents#contentsinsertcsscss-options
/// Works for both BrowserWindows and BrowserViews.
/// </summary>
/// <param name="isBrowserWindow">Whether the webContents belong to a BrowserWindow or not (the other option is a BrowserView)</param>
/// <param name="path">Absolute path to the CSS file location</param>
public void InsertCSS(bool isBrowserWindow, string path)
{
BridgeConnector.Socket.Emit("webContents-insertCSS", Id, isBrowserWindow, path);
}
private JsonSerializer _jsonSerializer = new JsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),

View File

@@ -173,6 +173,27 @@ module.exports = (socket) => {
electronSocket.emit('webContents-loadURL-error' + id, error);
});
});
socket.on('webContents-insertCSS', (id, isBrowserWindow, path) => {
if (isBrowserWindow) {
const browserWindow = getWindowById(id);
if (browserWindow) {
browserWindow.webContents.insertCSS(fs.readFileSync(path, 'utf8'));
}
}
else {
const browserViews = (global['browserViews'] = global['browserViews'] || []);
let view = null;
for (let i = 0; i < browserViews.length; i++) {
if (browserViews[i]['id'] + 1000 === id) {
view = browserViews[i];
break;
}
}
if (view) {
view.webContents.insertCSS(fs.readFileSync(path, 'utf8'));
}
}
});
function getWindowById(id) {
if (id >= 1000) {
return browserView_1.browserViewMediateService(id - 1000);

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +1,4 @@
import { BrowserWindow } from 'electron';
import { BrowserWindow, BrowserView } from 'electron';
import { browserViewMediateService } from './browserView';
const fs = require('fs');
let electronSocket;
@@ -222,6 +222,27 @@ export = (socket: SocketIO.Socket) => {
});
});
socket.on('webContents-insertCSS', (id, isBrowserWindow, path) => {
if (isBrowserWindow) {
const browserWindow = getWindowById(id);
if (browserWindow) {
browserWindow.webContents.insertCSS(fs.readFileSync(path, 'utf8'));
}
} else {
const browserViews: BrowserView[] = (global['browserViews'] = global['browserViews'] || []) as BrowserView[];
let view: BrowserView = null;
for (let i = 0; i < browserViews.length; i++) {
if (browserViews[i]['id'] + 1000 === id) {
view = browserViews[i];
break;
}
}
if (view) {
view.webContents.insertCSS(fs.readFileSync(path, 'utf8'));
}
}
});
function getWindowById(id: number): Electron.BrowserWindow | Electron.BrowserView {
if (id >= 1000) {