将javascript注入zombie.js [英] Injecting javascript into zombie.js

查看:85
本文介绍了将javascript注入zombie.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我想知道节点js和zombie js是否有能力将javascript文件注入无头浏览器,类似于你可以用phantomjs做的。



例如在幻影js中你会这样做:

  page.injectJs(amino / TVI.js)

我使用了phantomjs,它确实做了我想做的事情,但是我正在测试其他选项,因为使用幻像js需要高内存。

解决方案

您可以将脚本标记附加到文档对象中,因为它支持zombie中的DOM API。 / p>

以下示例显示如何将jquery插入zombie主页:

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

//从localhost加载页面
browser = new Browser()
browser.visit(http://zombie.labnotes.org/,function(){

assert.ok(browser.success);

//追加脚本标签
var injectScript = browser.document.createElement(script);
injectScript.setAttribute(type,text / javascript);
injectScript.setAttribute(src,http://code.jquery.com/jquery-1.11.0.min.js );

browser.body.appendChild(injectScript);

browser.wait(函数(窗口){
//确保插入新脚本标记
返回window.document.querySelectorAll(script)。length == 4;
},function(){
// jquery已准备好
assert.equal(浏览器。 evaluate($。fn.jquery),1.11.0);
console.log(browser.evaluate($('title')。text()));
} );
});


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.

解决方案

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()"));
  });
});

这篇关于将javascript注入zombie.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆