Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting javascript into zombie.js

Hi I was wondering if there is the ability in node js and zombie js to inject javascript files in to the headless browser, similar to what you can do with phantomjs.

For example in phantom js you would do:

page.injectJs("amino/TVI.js")

I have used phantomjs and it does do what I want it to do but however I am testing other options due to the high memory required by using phantom js.

like image 385
Charabon Avatar asked Apr 10 '14 13:04

Charabon


1 Answers

you can append script tag into document object since it support DOM API in zombie.

The following example shows how to insert jquery into zombie homepage:

var Browser = require("zombie");
var assert = require("assert");    

// Load the page from localhost
browser = new Browser()
browser.visit("http://zombie.labnotes.org/", function () {    

  assert.ok(browser.success);

  // append script tag
  var injectedScript = browser.document.createElement("script");
  injectedScript.setAttribute("type","text/javascript");
  injectedScript.setAttribute("src", "http://code.jquery.com/jquery-1.11.0.min.js");    

  browser.body.appendChild(injectedScript);    

  browser.wait(function(window) {
    // make sure the new script tag is inserted
    return window.document.querySelectorAll("script").length == 4;
  }, function() {
    // jquery is ready
    assert.equal(browser.evaluate("$.fn.jquery"), "1.11.0");
    console.log(browser.evaluate("$('title').text()"));
  });
});
like image 106
shawnzhu Avatar answered Sep 22 '22 00:09

shawnzhu