ajay
ajay

Reputation: 9680

jQuery not loading in webview in Electron app

I am using Electron framework to load a page in a webview. I want the page to be loaded just as a browser would load it without turning off node-integration. I tried various solutions I found on the web but to no avail.

I have started with electron-quick-start. This is my modified index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    <!-- All of the Node.js APIs are available in this renderer process. -->
    We are using Node.js <script>document.write(process.versions.node)</script>,
    Chromium <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.

    <webview id="foo" preload="./preload.js" src="https://www.icicibank.com/" style="display:inline-flex; width:1000px; height:800px" nodeIntegration></webview>
  </body>

  <script>
    // You can also require other files to run in this process
    require('./renderer.js')
  </script>
</html>

And this preload.js in the same root folder

window.onload = function() {
    window.$ = window.jQuery = require('jquery');
    console.log([$, jQuery ]);

    // I also tried the below:
    // but with no success
    // var script = document.createElement("script");
    // script.src = "https://code.jquery.com/jquery-2.1.4.min.js";
    // document.body.appendChild(script);
};

The console.log statement prints the values but when I open devtools for the webview by typing the below in the devtools console for the index.html page, I get the errors

var wv = document.getElementById("foo");
wv.openDevTools();

enter image description here

I also tried the solution described here Electron: jQuery is not defined but with the same result. Please help. Here is the complete code https://github.com/ajaykgp/electron-start

Upvotes: 1

Views: 2629

Answers (1)

GorvGoyl
GorvGoyl

Reputation: 49270

Do it this way:
main.js

const path = require('path')
const mainWindow = new BrowserWindow({
  webPreferences: {
    nodeIntegration: false,
    preload: path.join(__dirname, 'renderer.js')
  }
})

renderer.js

const path = require('path')
window.addEventListener('load', () => {

        //inject jquery to page
        window.$ = window.jQuery = require(path.join(__dirname, '/jquery-3.2.1.slim.min.js'));
});

Upvotes: 0

Related Questions