PhantomJS:在运行任何其他脚本之前注入一个脚本 [英] PhantomJS: injecting a script before any other scripts run

查看:195
本文介绍了PhantomJS:在运行任何其他脚本之前注入一个脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PhantomJS,我想注入一些JS,就像在其他<script>标记之前有一个额外的<script>标记一样.这是因为页面上的脚本使用了PhantomJS没有的某些功能,即Function.prototype.bindwindow.webkitRequestAnimationFrame.我有一个包含自定义实现的JS文件,我希望PhantomJS在运行页面上的脚本时使用它们.

Using PhantomJS, I'd like to inject some JS as if there was an extra <script> tag before any other <script> tags. This is because the scripts on the page use some functions that PhantomJS does not have, namely Function.prototype.bind and window.webkitRequestAnimationFrame. I have a JS file with custom implementations of the two and I'd like PhantomJS to use them when running the scripts on the page.

困难在于,如果我在page.open之前执行page.injectJs,该脚本将被注入到一个空页面中,并且不会被延续到正在打开的页面中.

The difficulty is that if I do page.injectJs before page.open, the script is injected into an empty page and is not carried over to the page being opened.

或者,如果我在page.open之后执行page.injectJs,则为时已晚,因为JavaScript错误(未定义的函数)已经发生.

Alternatively, if I do page.injectJs after page.open, it's too late as the JavaScript errors (undefined functions) have already occurred.

我发现了一种似乎可行的方法,但显然是一种破解:

I've found a way that appears to work, but is obviously a hack:

page.onResourceReceived = function() {
    page.injectJs('phantom-hacks.js')
};

这会多次注入(显然每个资源两次),但这没关系,因为我的脚本是幂等的.但是,我想知道执行此操作的正确方法:仅在运行页面上的任何脚本之前并且在运行该脚本之前,将其注入一次.

This injects it many times (twice for each resource, apparently), but that's okay because my script is idempotent. However, I'd like to know the proper way to do this: inject it only once and before any scripts on the page are run.

谢谢:)

推荐答案

除了挂接到事件之外,我认为没有适当"的方式来注入此类脚本. 我花了半年的时间与PhantomJs进行大规模合作,发现在所有错误开始发生之前,但在页面加载完成之后,没有办法注入.

I don't think there's a "proper" way to inject such script other than hooking to events. I've spent half a year working massively with PhantomJs and found no way to inject before all the errors start happening but after the page finished loading.

我会尝试通过onInitialized,onLoadStarted,onLoadFinished.在钩子内部,我将调用page.evaluate(),它将仅修改DOM以在您喜欢的任何地方添加此多余的东西.

I would try to go through onInitialized, onLoadStarted, onLoadFinished. Inside the hooks I would call to page.evaluate() which would just modify DOM to have this extra whatever place you like.

我认为其中一个(挂钩)应该给您所需的正确时间.

I think one of them (the hooks) should give you the right timing you want.

欢呼

这篇关于PhantomJS:在运行任何其他脚本之前注入一个脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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