Skip to content

How to inject jquery into Browserwindow #2048

Closed

Description

@SantoshSrinivas79

I am trying to replicated the selenium example but using electron only.

I am wondering how to inject jQuery and then set the query to "nice cats" and printout the search results.
I need jQuery to be injected first and then set the query using $("[name='q']")[0].value = "nice cats";

I can open google using the below app.js code.

var app = require('app')
var BrowserWindow = require('browser-window')
var ipc = require('ipc')

app.on('ready', function () {
  var mainWindow = new BrowserWindow({
    width: 800,
    height: 600
  });

  mainWindow.loadUrl('http://www.google.com');
  mainWindow.openDevTools();

  mainWindow.on('closed', function() {
    console.log("The page has been closed");
    mainWindow = null;
  });

  mainWindow.webContents.on('did-finish-load', function() {
    console.log(mainWindow.webContents.getUrl());
  });
});

I want to navigate to the next page using $.click and then print out the next results.

Can someone please help with this?

Activity

  1. frankhale commented on Jun 25, 2015

    @frankhale
    Contributor

    I'd probably do it this way. Instead of loading Google in the mainWindow using loadUrl I'd instead create a basic HTML page that contains a webview that loads Google. I'd then create a small JS file to load in the webview preload. This script would require jQuery like this:

    window.$ = window.jQuery = require('./bower_components/jquery/dist/jquery.min.js');

    Then in that small script I'd do whatever other code you need to do in order to intercept and manipulate elements on the Google page.

    At least that is what I am thinking off the top of my head. I'm sure there are other ways to do it.

  2. SantoshSrinivas79 commented on Jun 25, 2015

    @SantoshSrinivas79
    Author

    That works. Thank you. :-)

  3. SantoshSrinivas79 commented on Jun 25, 2015

    @SantoshSrinivas79
    Author

    Actually, I am still stuck on getting the elements of the page. How do I access them?

  4. frankhale commented on Jun 25, 2015

    @frankhale
    Contributor

    I'll try to come up with an example. Give me a few minutes.

  5. frankhale commented on Jun 25, 2015

    @frankhale
    Contributor

    Okay so disregard what I said above. It doesn't appear you can inject jQuery like that in a webview preload script. Try this, this works!

    index.html:

    <!DOCTYPE html>
    <html>
      <head>
        <title>jQuery injection into webview preload</title>
      </head>
      <body style="overflow:hidden;">
        <webview id="webview" preload="./manipulateGoogle.js" src="http://google.com" style="position:absolute;width:100%;height:100%;"></webview>
        <script>
          // need to have a script tag make webview work even if you don't plan to use it...
        </script>
      </body>
    </html>

    webview preload script (in this example name it manipulateGoogle.js)

    // injection technique borrowed from http://stackoverflow.com/questions/840240/injecting-jquery-into-a-page-fails-when-using-google-ajax-libraries-api
    window.onload = function() {
        var script = document.createElement("script");
        script.src = "https://code.jquery.com/jquery-2.1.4.min.js";
        script.onload = script.onreadystatechange = function() {
          $(document).ready(function() {
            $("#lst-ib").val("Hello, World!");
          });
        };
        document.body.appendChild(script);
    };

    main.js

    var app = require('app');
    var BrowserWindow = require('browser-window');
    require('crash-reporter').start();
    
    var mainWindow = null;
    
    app.on('window-all-closed', function() {
      if (process.platform != 'darwin')
        app.quit();
    });
    
    app.on('ready', function() {
      mainWindow = new BrowserWindow({
        width: 1024,
        height: 768,
        resizable: true
      });
    
      mainWindow.loadUrl('file://' + __dirname + '/index.html');
      mainWindow.focus();
      mainWindow.on('closed', function() {
        mainWindow = null;
      });
    });

    Yay! It works! w00t!

    manipulategoogleusingjquery

  6. SantoshSrinivas79 commented on Jun 25, 2015

    @SantoshSrinivas79
    Author

    @frankhale Thanks a ton! My head was spinning understanding what is available in which process!

    Thank you! :-)

  7. frankhale commented on Jun 25, 2015

    @frankhale
    Contributor

    You're welcome! Let me know if you have any other questions. I'll try to help out if I can!

  8. Deliaz commented on Feb 29, 2016

    @Deliaz

    frankhale thanks, great info.
    Is that possible in manipulateGoogle.js inject locally-stored scripts with relative path?

  9. frankhale commented on Feb 29, 2016

    @frankhale
    Contributor
  10. Deliaz commented on Feb 29, 2016

    @Deliaz

    Thx,
    Is there any way to do this in the case of multiple scripts (without concatenation)?

  11. frankhale commented on Feb 29, 2016

    @frankhale
    Contributor

    I guess you could load a script that in turn loads other scripts to get around only being able to pass one script to preload tag.

  12. Deliaz commented on Feb 29, 2016

    @Deliaz

    Yeah, I did so.
    And it looks like I'm not able to use relative paths to scripts.

  13. 14 remaining items

  14. frankhale commented on Mar 30, 2016

    @frankhale
    Contributor

    So yeah, Electron has built in API to do IPC and the docs are here:

    https://github.com/atom/electron/blob/master/docs/api/ipc-main.md
    https://github.com/atom/electron/blob/master/docs/api/ipc-renderer.md

    I've only briefly used the in-built IPC API so can't really comment much on it. I've also used Socket IO as a "IPC" mechanism and found it to work rather nicely. You could probably use other APIs to communicate back and forth but I haven't really explored it because Socket IO worked well for me in this regard.

  15. 3goats commented on Mar 31, 2016

    @3goats

    Thanks again @frankhale.

    Going back to your manipulateGoogle.js example which now after further investigation I understand whats happening. However, most of my page elements are created and built using AJAX requests which means there's nothing for the jquery selectors to find until the page is built.

    Appreciate, this is more of a jquery question (maybe), but is there a way to wait until the subsequent page build completes before firing $(document).ready ?

  16. frankhale commented on Mar 31, 2016

    @frankhale
    Contributor

    (I haven't tried this but...) If you have control over the code that you are loading (eg you can edit it) why not set up a callback in your webview preload and then when your page gets done loading all it's ajax stuff then call the callback from the code loaded in the webview to notify it that your page is done doing everything so you can then manipulate it as needed from the webview preload script.

  17. 3goats commented on Mar 31, 2016

    @3goats

    Yeah, thats the problem, I don't have control of the code in the pages I'm loading.

  18. frankhale commented on Mar 31, 2016

    @frankhale
    Contributor

    okay no problem, here is a possible work around. Maybe there is something you can look for in the page when you know the page may be finished loading and then trigger some code to manipulate the results. I'm thinking set up an interval to periodically do something and then remove the interval after some time or maybe even setup a timeout to run the manipulate code after a number of seconds have passed.

  19. TimNZ commented on Aug 7, 2016

    @TimNZ

    @frankhale You said you couldn't require jquery in a preload script
    #2048 (comment)

    Why was that? I'm doing this in 1.3.2 and it appears to work fine:

    window.onload = function() {
        const {webFrame,remote} = require('electron')
        var appOptions = remote.getGlobal('app_options')
        let jq = require('jquery')
        jq(document).ready(() => {
            setInterval(() => {
                var a = jq('a[id=Dashboard]')
                if (a.length)
                    a.text('Tim')
    
            })
        })
    };
    
  20. MarshallOfSound commented on Aug 7, 2016

    @MarshallOfSound
    Member

    @TimNZ That's because you are waiting for the window load event before require jQuery. This means the document object is fully populated and the DOM is rendered.

    You can't do what are you doing without the onload function

  21. dizawish commented on May 27, 2017

    @dizawish

    Can by any chance confirm, that the above example of manipulation www.google.com still works?
    Got up to the point of preloading the script, in which i put an alert(); and works fine. But i cant get the text swapping work with the jquery.
    Thanx

  22. frankhale commented on May 29, 2017

    @frankhale
    Contributor

    @dizawish I don't know what is going on now. I just tried the google manipulation code I wrote a long time ago and it fails in the preload script because window.onload never seems to be called or it's called before preload script loads now. This is different behavior to past Electron releases so I'm not really sure. Although I did manage to get it to work by refactoring my preload script a bit. I no longer rely on window.onload but instead use an interval to check the document.readystate and then inject jQuery, change the text in the google search input field and clear the interval. I've tested this against Electron 1.6.10 and 1.7.2 (beta).

    The following repository has this code:

    https://github.com/frankhale/electron-inject-jquery-webview-example

  23. michaelgv commented on Sep 28, 2017

    @michaelgv

    @frankhale @dizawish Electron has changed, it appears window.onload may not of been fired ever, however updating the script to something like this will fix it:

    document.addEventListener("DOMContentLoaded", function(event) {
    	setTimeout(function() {
    		alert(document.domain); // "google.com"
    	},1000);
    });

    DOMContentLoaded is always fired, so listening for it is the best way to inject jQuery/do whatever you need to do here. I put it in a setTimeout for fun, however it's not necessary. Made a pull req on your repo @frankhale: https://github.com/frankhale/electron-inject-jquery-webview-example/pull/1

  24. frankhale commented on Sep 28, 2017

    @frankhale
    Contributor

    Thank you so much @michaelgv for the pull request. I've merged it.

  25. michaelgv commented on Sep 28, 2017

    @michaelgv

    @frankhale np, another way to do it is with vanilla JS, or directly importing the jQuery library in your google.js file, vanilla way:

    document.addEventListener("DOMContentLoaded", function(event) {
    	document.getElementById("lst-ib").value='Electron.js';
    });
  26. aryaveersr commented on May 7, 2020

    @aryaveersr

    @frankhale A Easy way to load HTML file is : window.loadFile('index.html') than that __dir or whatever

  27. fastcodeco commented on Dec 1, 2020

    @fastcodeco

    Tks it worked

    Okay so disregard what I said above. It doesn't appear you can inject jQuery like that in a webview preload script. Try this, this works!

    index.html:

    <!DOCTYPE html>
    <html>
      <head>
        <title>jQuery injection into webview preload</title>
      </head>
      <body style="overflow:hidden;">
        <webview id="webview" preload="./manipulateGoogle.js" src="http://google.com" style="position:absolute;width:100%;height:100%;"></webview>
        <script>
          // need to have a script tag make webview work even if you don't plan to use it...
        </script>
      </body>
    </html>
    

    webview preload script (in this example name it manipulateGoogle.js)

    // injection technique borrowed from http://stackoverflow.com/questions/840240/injecting-jquery-into-a-page-fails-when-using-google-ajax-libraries-api
    window.onload = function() {
        var script = document.createElement("script");
        script.src = "https://code.jquery.com/jquery-2.1.4.min.js";
        script.onload = script.onreadystatechange = function() {
          $(document).ready(function() {
            $("#lst-ib").val("Hello, World!");
          });
        };
        document.body.appendChild(script);
    };

    main.js

    var app = require('app');
    var BrowserWindow = require('browser-window');
    require('crash-reporter').start();
    
    var mainWindow = null;
    
    app.on('window-all-closed', function() {
      if (process.platform != 'darwin')
        app.quit();
    });
    
    app.on('ready', function() {
      mainWindow = new BrowserWindow({
        width: 1024,
        height: 768,
        resizable: true
      });
    
      mainWindow.loadUrl('file://' + __dirname + '/index.html');
      mainWindow.focus();
      mainWindow.on('closed', function() {
        mainWindow = null;
      });
    });

    Yay! It works! w00t!

    manipulategoogleusingjquery

  28. Novivy commented on Dec 17, 2020

    @Novivy

    Note: You need to enable the webview tag for this to load

      webPreferences: {
    
                webviewTag: true
            
            },
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions