Skip to content

Commit 73a3e33

Browse files
committed
Add executeJavaScript method to WebContents
1 parent a15db71 commit 73a3e33

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

src/ElectronNET.API/WebContents.cs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,37 @@ public Task<bool> PrintToPDFAsync(string path, PrintToPDFOptions options = null)
244244
return taskCompletionSource.Task;
245245
}
246246

247+
/// <summary>
248+
/// Evaluates script code in page.
249+
/// </summary>
250+
/// <param name="code">The code to execute.</param>
251+
/// <param name="userGesture">if set to <c>true</c> simulate a user gesture.</param>
252+
/// <returns>The result of the executed code.</returns>
253+
/// <remarks>
254+
/// <para>
255+
/// In the browser window some HTML APIs like `requestFullScreen` can only be
256+
/// invoked by a gesture from the user. Setting `userGesture` to `true` will remove
257+
/// this limitation.
258+
/// </para>
259+
/// <para>
260+
/// Code execution will be suspended until web page stop loading.
261+
/// </para>
262+
/// </remarks>
263+
public Task<object> ExecuteJavaScriptAsync(string code, bool userGesture = false)
264+
{
265+
var taskCompletionSource = new TaskCompletionSource<object>();
266+
267+
BridgeConnector.Socket.On("webContents-executeJavaScript-completed", (result) =>
268+
{
269+
BridgeConnector.Socket.Off("webContents-executeJavaScript-completed");
270+
taskCompletionSource.SetResult(result);
271+
});
272+
273+
BridgeConnector.Socket.Emit("webContents-executeJavaScript", Id, code, userGesture);
274+
275+
return taskCompletionSource.Task;
276+
}
277+
247278
/// <summary>
248279
/// Is used to get the Url of the loaded page.
249280
/// It's usefull if a web-server redirects you and you need to know where it redirects. For instance, It's useful in case of Implicit Authorization.

src/ElectronNET.Host/api/webContents.js

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/ElectronNET.Host/api/webContents.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,11 @@ export = (socket: Socket) => {
7474
});
7575
});
7676

77+
socket.on('webContents-executeJavaScript', async (id, code, userGesture = false) => {
78+
const result = await getWindowById(id).webContents.executeJavaScript(code, userGesture);
79+
electronSocket.emit('webContents-executeJavaScript-completed', result);
80+
});
81+
7782
socket.on('webContents-getUrl', function (id) {
7883
const browserWindow = getWindowById(id);
7984
electronSocket.emit('webContents-getUrl' + id, browserWindow.webContents.getURL());

0 commit comments

Comments
 (0)