Injecting Javascript Inside Electron Webview

Recently I created a Web browser-based on Javascript framework and library Electron and React.js Respectively and with Webpack. One of browser Requirement was to inject JS inside of the webview. A Javascript that runs inside of Website running inside webview.

Image for post
Image for post

Fortunately, this can be done by preload; a Preload is one of the parameters of Webview that let you inject Whole JS file inside of a webview rendered website. The file will then have access to all the internal browser API like window and document.

You can inject a preload file like ๐Ÿ‘‡

Image for post
Image for post

There are a couple of things you need to know about the preload while working with dev environment you might easily pass the relative path. Still, at the time of production, you need to make sure that your preload file is accessible via File Protocol since preload only accept the path of File protocol, I had a similar issue with me react based browser, At the time of production, it was not able to get the path of preload file.

Also in the preload file will reload in every single time a dom content loaded, but if you are navigating a SPA, there will be no reloaded and no dom Content loaded event as well. So you will have to look for the webview on did-start-loading and did-stop-loading event. and on received of these events, you can send a message to listener setup on your preload file like this ๐Ÿ‘‡

Image for post
Image for post

You will have access to electron API, and Its functionality. And to check if the dom content is currently loaded, you can use this in your preload file. ๐Ÿ‘‡

Image for post
Image for post

Just like this, now can change anything inside of a website since you the access to the document API, you can select them, append elements, hide elements, etc.

Thatโ€™s it.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store