Hello, internet!

How to Control WebViews in your Electron App

Author: KorbsStudio KorbsStudio

We’ll learn how to add functions to your Electron app that allows you and the user, if needed, to control the webview. Just like a modern web browser there are controls in the top area of the browser UI that lets you do actions like go back, go forward, refresh the page, and more. For now, we’re going to add a back, forward, and refresh button.

Assuming you already have your Electron app setup, we need to add a configuration under BrowserWindow in our main process. You’ll need to enable the webviewTag API like this:

...
    webPreferences: {
        webviewTag: true
    }
...

Then we can add a webview to the index.html for us to control later. We’ll need to also give it an id name so we can identity the webview in our functions to control it:

<webview id="primary" src="https://userverge.com/"></webview>

While we’re adding that, let’s add our buttons with functions we will setup soon:

<div class="controls">
    <buttons onclick="PrimaryGoBack();">Go back</button>
    <buttons onclick="PrimaryGoForward();">Go forward</button>
    <buttons onclick="PrimaryRefresh();">Refesh</button>
</div>

Then we’ll add a file to put our functions in and name it webview-controls.js. We’ll use var to indentity each webview we use in the app:

var primary = document.getElementById('primary')

function PrimaryGoBack() {primary.goBack();}
function PrimaryGoForward() {primary.goForward();}
function PrimaryRefresh() {primary.reload();}

Simply star the app and try out the controls.

Also look at:

https://www.electronjs.org/docs/latest/api/webview-tag