Injecting Javascript Inside Electron Webview

Raja Osama
2 min readOct 29, 2020

--

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.

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 πŸ‘‡

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 πŸ‘‡

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. πŸ‘‡

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.

--

--

Raja Osama
Raja Osama

Written by Raja Osama

πŸ‘‹ Hi, I'm Raja Osama, a polyglot rockstar software engineer who loves to create fascinating applications using JavaScript-based tech stack. πŸ’»

No responses yet