Using jQuery in Zombie.js
Asked Answered
C

2

6

I realize there are other libraries designed for the use of jQuery-like syntax with Zombie, but for my purposes, I specifically want/need to use jQuery itself in order to maintain compatibility with some earlier-written code.

I installed the npm jQuery package, and I've been trying to import jQuery into my script and then initialize it with the window returned by Zombie like so:

var Zombie= require("zombie"),
$ = require("jquery")
, zombie = new Zombie();

zombie.visit("http://www.mysite.com", function (err, browser, status) {
  if(err) {
    console.log("Error: " + err);
  }

  //Initialize a new jQuery instance with the current window returned by Zombie
  var $window = $(browser.window);
  //Get an actual jQuery object so we can search for stuff
  var document = $window("body");

  var inputBoxUsername = document.find("input#username");

  console.log(inputBoxUsername.html());
});

This isn't working, as it says that there's no html() function, and jQuery doesn't actually seem to be returning the object I'm expecting.

Is there a way to use jQuery with Zombie?

Carboxylate answered 27/12, 2013 at 21:22 Comment(2)
What is the value of i?Lollipop
Sorry, I failed at editing. It was supposed to be document.Carboxylate
C
3

If your site is already loading jquery, you can use the loaded jQuery straight away, which in some cases is far easier.

var document = browser.window.$("body");

Will work as expected, since it is a jQuery object.

I think that you can add script files anyway so you could dinamically add jQuery and use it as I just mentioned.

Hope this helps!

Cushitic answered 17/3, 2014 at 11:35 Comment(0)
P
1

If the page you are working with doesn't include jQuery, and you are only retrieving data, then try using Cheerio on top of Zombie:

zombie.visit("http://example.com", function () {
  var $ = cheerio.load(browser.html());
  console.log($('title').text());
}
Papilionaceous answered 20/3, 2017 at 23:19 Comment(1)
Best possible implementation!Constantino

© 2022 - 2024 — McMap. All rights reserved.